<?php
namespace app\api\service\pay\lakala;

use app\api\model\LakalaEcApply;
use app\api\service\pay\PlatformInterface;
use app\api\service\pay\lakala\ApiService;
use think\exception\ValidateException;
use app\api\model\Order;
use app\api\model\OrderLakala;
use app\api\model\OrderRefund;
use app\api\model\OrderRefundLakala;
use app\api\model\OrderShansong;
use app\api\model\Shop;
use app\api\model\SenderInfo;
use app\api\model\ReceiverInfo;
use app\api\model\Courier;
use app\api\model\MallDealLog;
use app\api\model\AppConfig;
use think\facade\Db;
use think\facade\Log;
use app\common\service\LakalaPayService;
use CURLFile; // 引入 CURLFile 类

// 拉卡拉
class LakalaAdapter implements PlatformInterface
{

    public $ApiService;
    protected $config;//配置

    // sdk---v3-请求状态码
    const REQ_STATUS_SUCCESS = 'BBS00000';//成功

    //  sdk---v3-回调状态码
    const BACK_STATUS_SUCCESS = 'SUCCESS';//成功


    // sdk---v3----状态码字符串
    public function getV3StatusStr($status_str='')
    {
        $statusMap = [
            self::REQ_STATUS_SUCCESS => '成功',
            self::BACK_STATUS_SUCCESS => '执行成功',
        ];

        return isset($statusMap[$status_str]) ? $statusMap[$status_str] : '成功';
    }


    // 钱包类型
    const pay_account_type_wechat  = "WECHAT"; //微信钱包
    const pay_account_type_alipay  = "ALIPAY"; //支付宝钱包
    const pay_account_type_union  = "UQRCODEPAY ";//银联钱包
    const pay_account_type_best  = "BESTPAY"; //翼支付钱包
    const pay_account_type_suning  = "SUNING";//苏宁钱包
    const pay_account_type_lakala  = "LKLACC";//拉卡拉钱包
    const pay_account_type_uncs  = "NUCSPAY";//网联钱包
    const pay_account_type_jd  = "JDPAY";//京东钱包

    // 接入方式
    const pay_trans_type_native  = 41;//ALIPAY，云闪付支持，京东白条分期
    const pay_trans_type_jsapi  = 51;//微信公众号支付，支付宝服务窗支付，银联JS支付，翼支付JS支付, 拉卡拉钱包支付, 支付宝小程序支付
    const pay_trans_type_wechat_app  = 61;//微信小程序支付
    const pay_trans_type_wechat_mini  = 71;//微信APP支付

    /*
    * $config: 配置信息
    * $pro_dev: true正式域名 false测试域名
    */
    public function __construct(array $config)
    {
        $this->config = $config;
        $this->ApiService=new ApiService($config);
    }


// ------------------------------------具体实现方法-----------------------------------



// ----------------------------------token接口-------------------------------------

// 费率类型
// CREDIT_CARD	贷记卡费率（云闪付必传）
// DEBIT_CARD	借记卡费率（云闪付必传，此费率类型必须上送封顶值 topFee）
// WECHAT	微信（必传）
// LINE_WECHAT	线上微信(资金类业务不需要传)
// ALIPAY	支付宝（必传）
// UNIONPAY_WALLET_DEBIT_FEE	银联二维码借记卡（此费率类型必须上送封顶值 topFee）资金类业务同借记卡费率）
// UNIONPAY_WALLET_CREDIT_FEE	银联二维码贷记卡（资金类业务同贷记卡费率）
// YSF_DISCOUNT_DEBIT_FEE	云闪付借记-优惠（资金类业务不需要传）
// YSF_DISCOUNT_CREDIT_FEE	云闪付贷记-优惠（资金类业务不需要传）
// YL_DISCOUNT_DEBIT_FEE	银联二维码借记-优惠（资金类业务不需要传）
// YL_DISCOUNT_CREDIT_FEE	银联二维码贷记-优惠（资金类业务不需要传）
// ALIPAY_DISCOUNT_FEE,	支付宝优惠费率（资金类业务不需要传）
// SCAN_PAY_SECOND	扫码d0费率（扫码D0结算必传）
// CARD_SECOND刷卡D0费率（刷卡D0结算必传）
// MER_WITHDRAWAL_SECOND 商户秒提费率
// YSF_LE_1000	云闪付小额优惠费率（资金类业务不需要传）

// 附件类型
// ID_CARD_FRONT	身份证正⾯（必传）
// ID_CARD_BEHIND	身份证反⾯（必传）
// BUSINESS_LICENCE	营业执照照⽚（企业必传）
// BANK_CARD	银行卡（对私必传，企业对公传）
// AGREE_MENT	协议（入网协议必传）
// OPENING_PERMIT	开户许可证（企业对公需要传，对私不传）
// CHECKSTAND_IMG	收银台照片(必传)
// SHOP_OUTSIDE_IMG	上传门头照片(必传)
// SHOP_INSIDE_IMG	商铺内部照片(必传)
// OTHERS	其他 无对应类型图片，请传其他类型
// SETTLE_ID_CARD_FRONT	结算人身份证人像面
// SETTLE_ID_CARD_BEHIND	结算人身份证国徽面
// LETTER_OF_AUTHORIZATION	法人授权涵

    // 进件
    public function merchant($params=[])
    {
        // 验证数据
        try {
            validate([
                'appid'  => 'require', // 应用ID
                'app_store_id'  => 'require', // 商户ID
                'app_type'  => 'require', // 应用类型
//                'store_name'  => 'require', // 商户名称
                'latitude'  => 'require', // 经度
                'longtude'  => 'require', // 纬度
//                'userNo' => 'require|unique:shop', // 用户编号，唯一
                'email' => 'require|email', // 邮箱，必须是有效的邮箱格式
                'mobile' => 'require', // 手机号
                'merRegName' => 'require', // 商户注册名称
                'merType' => 'require|in:TP_MERCHANT,TP_PERSONAL', // 商户注册类型
                'merName' => 'require', // 商户名称
                'merAddr' => 'require', // 商户详细地址
                'provinceCode' => 'require', // 省代码
                'cityCode' => 'require', // 市代码
                'countyCode' => 'require', // 区县代码
                'source' => 'require|in:APP,H5', // 进件来源
                'businessContent' => 'require', // 商户经营内容
                'larName' => 'require', // 法人姓名
                'larIdType' => 'require|in:01,02,03,04,10,11,12,13,99', // 法人证件类型
                'larIdCard' => 'require', // 法人证件号码
                'larIdCardStart' => 'require', // 法人证件开始日期
                'larIdCardEnd' => 'require', // 法人证件过期时间
                'contactMobile' => 'require', // 商户联系人手机号码
                'contactName' => 'require', // 商户联系人姓名
                'openningBankCode' => 'require', // 结算账户开户行号
                'openningBankName' => 'require', // 结算账户开户行名称
                'clearingBankCode' => 'require', // 结算账户清算行号
                'settleProvinceCode' => 'require', // 结算信息省份代码
                'settleProvinceName' => 'require', // 结算信息省份名称
                'settleCityCode' => 'require', // 结算信息城市代码
                'settleCityName' => 'require', // 结算信息城市名称
                'accountNo' => 'require', // 结算人银行卡号
                'accountName' => 'require', // 结算人账户名称
                'accountType' => 'require', // 结算账户类型
                'accountIdCard' => 'require', // 结算人证件号码
//                'attchments' => 'require', // 附件信息集合
                'settleType' => 'require', // 结算类型
//                'bizContent' => 'require', // 业务扩展信息

                'agree_ment' => 'require|unique:shop',
                'bank_card' => 'require',
                'id_card_front' => 'require',
                'id_card_behind' => 'require',
                'shop_outside_img' => 'require',
                'shop_inside_img' => 'require',
                'business_licence' => 'require',
//                'opening_permit' => 'require',
                'checkstand_img' => 'require',
            ])->message([
                'appid.require'  => 'appid必须传递',
                'app_store_id.require'  => 'app_store_id必须传递',
                'app_type.require'  => 'app_type必须传递',
//                'store_name.require'  => 'store_name必须传递',
                'latitude.require'  => 'latitude必须传递',
                'longtude.require'  => 'longtude必须传递',
//                'userNo.require' => 'userNo必须传递',
//                'userNo.unique' => 'userNo必须唯一',
                'email.require' => 'email必须传递',
                'email.email' => 'email格式不正确',
                'mobile.require' => 'mobile必须传递',
//                'busiCode.require' => 'busiCode业务类型必须传递',
                'merRegName.require' => 'merRegName商户注册名称必须传递',
                'merType.require' => 'merType商户注册类型必须传递',
                'merType.in' => 'merType商户注册类型取值必须为TP_MERCHANT或TP_PERSONAL',
                'merName.require' => 'merName商户名称必须传递',
                'merAddr.require' => 'merAddr商户详细地址必须传递',
                'provinceCode.require' => 'provinceCode省代码必须传递',
                'cityCode.require' => 'cityCode市代码必须传递',
                'countyCode.require' => 'countyCode区县代码必须传递',
                'source.require' => 'source进件来源必须传递',
                'source.in' => 'source进件来源取值必须为APP或H5',
                'businessContent.require' => 'businessContent商户经营内容必须传递',
                'larName.require' => 'larName法人姓名必须传递',
                'larIdType.require' => 'larIdType法人证件类型必须传递',
                'larIdType.in' => 'larIdType法人证件类型取值必须为01,02,03,04,10,11,12,13,99之一',
                'larIdCard.require' => 'larIdCard法人证件号码必须传递',
                'larIdCardStart.require' => 'larIdCardStart法人证件开始日期必须传递',
                'larIdCardEnd.require' => 'larIdCardEnd法人证件过期时间必须传递',
                'contactMobile.require' => 'contactMobile商户联系人手机号码必须传递',
                'contactName.require' => 'contactName商户联系人姓名必须传递',
                'openningBankCode.require' => 'openningBankCode结算账户开户行号必须传递',
                'openningBankName.require' => 'openningBankName结算账户开户行名称必须传递',
                'clearingBankCode.require' => 'clearingBankCode结算账户清算行号必须传递',
                'settleProvinceCode.require' => 'settleProvinceCode结算信息省份代码必须传递',
                'settleProvinceName.require' => 'settleProvinceName结算信息省份名称必须传递',
                'settleCityCode.require' => 'settleCityCode结算信息城市代码必须传递',
                'settleCityName.require' => 'settleCityName结算信息城市名称必须传递',
                'accountNo.require' => 'accountNo结算人银行卡号必须传递',
                'accountName.require' => 'accountName结算人账户名称必须传递',
                'accountType.require' => 'accountType结算账户类型必须传递',
                'accountIdCard.require' => 'accountIdCard结算人证件号码必须传递',
//                'attchments.require' => 'attchments附件信息集合必须传递',
                'settleType.require' => 'settleType结算类型必须传递',
//                'bizContent.require' => 'bizContent业务扩展信息必须传递',
                'mcc.require' => 'mcc商户MCC编号必须传递',

                 'agree_ment.require' => 'agree_ment入网协议必传',
                'bank_card.require' => 'bank_card银行卡号必传',
                'id_card_front.require' => 'id_card_front身份证正⾯必传',
                'id_card_behind.require' => 'id_card_behind身份证反⾯必传',
                'shop_outside_img.require' => 'shop_outside_img门头照片必传',
                'shop_inside_img.require' => 'shop_inside_img店铺内部照片必传',
                'business_licence.require' => 'business_licence营业执照照⽚必传',
//                'opening_permit.require' => 'opening_permit开户许可证必传',
                'checkstand_img.require' => 'checkstand_img收银台照片必传',

            ])->check($params);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        $data['userNo']=(int)$this->config['user_no'];//商户归属用户信息
        $data['email']=$params['email']??'';//商户邮箱
        $data['busiCode']=$params['busiCode']??'WECHAT_PAY';//业务类型
        $data['merRegName']=$params['merRegName']??'';//商户注册名称
        $data['merType']=$params['merType']??'';//商户注册类型TP_MERCHANT:企业TP_PERSONAL:⼩微个⼈
        $data['merName']=$params['merName']??'';//商户名称(经营名称
        $data['merAddr']=$params['merAddr']??'';//商户详细地址
        $data['provinceCode']=$params['provinceCode']??'';//省代码
        $data['cityCode']=$params['cityCode']??'';//市代码
        $data['countyCode']=$params['countyCode']??'';//区县代码
        $data['licenseName']=$params['licenseName']??'';//营业执照名称(可选)
        $data['licenseNo']=$params['licenseNo']??'';//营业执照号码(可选)
        $data['licenseDtStart']=$params['licenseDtStart']??'';//营业执照开始时间(可选)
        $data['licenseDtEnd']=$params['licenseDtEnd']??'';//营业执照过期时间(可选)
        $data['latitude']=$params['latitude']??'';//经度
        $data['longtude']=$params['longtude']??'';//纬度
        $data['source']=$params['source']??'';//进件来源(APP, H5) 2选1
        $data['businessContent']=$params['businessContent']??'';//商户经营内容
        $data['isLegalPerson']=$params['isLegalPerson']??true;//是否法⼈进件true false(可选)
        $data['larName']=$params['larName']??'';//法⼈姓名
        $data['larIdType']=$params['larIdType']??'';//法⼈证件类型
        $data['larIdCard']=$params['larIdCard']??'';//法⼈证件号码
        $data['larIdCardStart']=$params['larIdCardStart']??'';//法⼈证件开始⽇期
        $data['larIdCardEnd']=$params['larIdCardEnd']??'';//法⼈证件过期时间
        $data['contactMobile']=$params['contactMobile']??'';//商户联系⼈⼿机号码
        $data['contactName']=$params['contactName']??'';//商户联系⼈姓名
        $data['openningBankCode']=$params['openningBankCode']??'';//结算账户开户⾏号
        $data['openningBankName']=$params['openningBankName']??'';//结算账户开户⾏名称
        $data['clearingBankCode']=$params['clearingBankCode']??'';//结算账户清算⾏号
        $data['settleProvinceCode']=$params['settleProvinceCode']??'';//结算信息省份代码
        $data['settleProvinceName']=$params['settleProvinceName']??'';//结算信息省份名称
        $data['settleCityCode']=$params['settleCityCode']??'';//结算信息城市代码
        $data['settleCityName']=$params['settleCityName']??'';//结算信息城市名称
        $data['accountNo']=$params['accountNo']??'';//结算人银行卡号
        $data['accountName']=$params['accountName']??'';//结算人账户名称
        $data['accountType']=$params['accountType']??'';//结算账户类型57 对公 58 对私
//        $data['accountIdType']=$params['accountIdType']??'';//结算⼈证件类型(可选)
        $data['accountIdCard']=$params['accountIdCard']??'';//结算⼈证件号码
        $data['accountIdDtStart']=$params['accountIdDtStart']??'';//结算⼈证件开始时间(可选)
        $data['accountIdDtEnd']=$params['accountIdDtEnd']??'';//结算⼈证件过期时间(可选)

        $attchmentsTypeMap = [
//            'agree_ment' => 'AGREE_MENT',
            'bank_card' => 'BANK_CARD',
            'others' => 'OTHERS',
            'id_card_front' => 'ID_CARD_FRONT',
            'id_card_behind' => 'ID_CARD_BEHIND',
            'shop_outside_img' => 'SHOP_OUTSIDE_IMG',
            'shop_inside_img' => 'SHOP_INSIDE_IMG',
            'business_licence' => 'BUSINESS_LICENCE',
            'opening_permit' => 'OPENING_PERMIT',
            'checkstand_img' => 'CHECKSTAND_IMG',
            'settle_id_card_front' => 'SETTLE_ID_CARD_FRONT',
            'settle_id_card_behind' => 'SETTLE_ID_CARD_BEHIND',
            'letter_of_authorization' => 'LETTER_OF_AUTHORIZATION'
        ];
        $attachments = [];
        foreach ($params as $key => $value) {
            if (isset($attchmentsTypeMap[$key]) && !empty($value)) {
                $attachments[] = [
                    'id' => $value,
                    'type' => $attchmentsTypeMap[$key]
                ];
            }
        }
        $data['attchments'] = $attachments;

        if (!empty($params['bizContent'])) {
            if (!is_array($params['bizContent'])) {
                $params['bizContent'] = json_decode($params['bizContent'], true);
            }
            $data['bizContent'] = $params['bizContent'];
        } else {
            $data['bizContent'] = $this->config['default_bizContent'];
        }

        $data['settleType']=$params['settleType']??'D1';//结算类型 D0秒到， D1次日结算
//        $data['shopId']=$params['shopId']??'';//⽹点代码(可选)
        $data['settlementType']=$params['settlementType']??'AUTOMATIC';//结算方式MANUAL:手动结算(结算至拉卡拉APP钱包),AUTOMATIC:自动结算到银行卡,REGULAR:定时结算（仅企业商户支持）
//        $data['regularSettlementTime']=$params['regularSettlementTime']??'';//定时结算时间(可选)
//        $data['contractNo']=$params['contractNo']??'';//电子合同编号(可选)

//        dd($data);
        foreach ($data['bizContent']['fees'] as &$v){
            $v['feeValue'] = (double)$v['feeValue'];
        }
        $data['bizContent']['activityId'] = (int)$data['bizContent']['activityId'];
        $data['bizContent']['mcc'] = $params['mcc'];
        $data['bizContent']['termNum'] = $params['termNum'];
        $data['userNo'] = (int)$data['userNo'];


        $res = $this->ApiService->sendTokenUnite('merchant',$data);

        if ( isset($res['error']) ) {
            return $this->ApiService->returnTokenUnite($res);
        }
        //入库
        //附件
        $data['agree_ment']= $params['agree_ment']??'';
        $data['bank_card'] = $params['bank_card']??'';
        $data['others']    = $params['others']??'';
        $data['id_card_front']=$params['id_card_front']??'';
        $data['id_card_behind']=$params['id_card_behind']??'';
        $data['shop_outside_img']=$params['shop_outside_img']??'';
        $data['shop_inside_img']=$params['shop_inside_img']??'';
        $data['business_licence']=$params['business_licence']??'';
        $data['opening_permit']=$params['opening_permit']??'';
        $data['checkstand_img']=$params['checkstand_img']??'';
        $data['settle_id_card_front']=$params['settle_id_card_front']??'';
        $data['settle_id_card_behind']=$params['settle_id_card_behind']??'';
        $data['letter_of_authorization']=$params['letter_of_authorization']??'';
        $shop_data = [
            'appid'     => $params['appid'],
            'app_type'  => get_app_type_int($params['app_type']),
            'pro_dev'   => get_pro_dev_int($params['app_type']),
            'store_id'   => $params['app_store_id'] ?? 0,
            'merchantNo' => $res['merchantNo'],
            'status'     => Shop::getLklApproveStatusInt($res['status']),
        ];
        $shop_data = array_merge($shop_data,$data);

        $shopModel = new Shop();
//        $shop = $shopModel->save($shop_data);
        if ( $shopModel->save($shop_data) ) {
            return $this->ApiService->returnTokenUnite($res);
        }

    }

    public function merchant_update($params=[])
    {
        // 验证数据
        try {
            validate([
                'merchantNo'  => 'require', // 商户号
                'appid'  => 'require', // 应用ID
                'app_store_id'  => 'require', // 商户ID
                'app_type'  => 'require', // 应用类型
//                'store_name'  => 'require', // 商户名称
                'latitude'  => 'require', // 经度
                'longtude'  => 'require', // 纬度
//                'userNo' => 'require|unique:shop', // 用户编号，唯一
                'email' => 'require|email', // 邮箱，必须是有效的邮箱格式
//                'busiCode' => 'require', // 业务类型
                'merRegName' => 'require', // 商户注册名称
                'merType' => 'require|in:TP_MERCHANT,TP_PERSONAL', // 商户注册类型
                'merName' => 'require', // 商户名称
                'merAddr' => 'require', // 商户详细地址
                'provinceCode' => 'require', // 省代码
                'cityCode' => 'require', // 市代码
                'countyCode' => 'require', // 区县代码
                'source' => 'require|in:APP,H5', // 进件来源
                'businessContent' => 'require', // 商户经营内容
                'larName' => 'require', // 法人姓名
                'larIdType' => 'require|in:01,02,03,04,10,11,12,13,99', // 法人证件类型
                'larIdCard' => 'require', // 法人证件号码
                'larIdCardStart' => 'require', // 法人证件开始日期
                'larIdCardEnd' => 'require', // 法人证件过期时间
                'contactMobile' => 'require', // 商户联系人手机号码
                'contactName' => 'require', // 商户联系人姓名
                'openningBankCode' => 'require', // 结算账户开户行号
                'openningBankName' => 'require', // 结算账户开户行名称
                'clearingBankCode' => 'require', // 结算账户清算行号
                'settleProvinceCode' => 'require', // 结算信息省份代码
                'settleProvinceName' => 'require', // 结算信息省份名称
                'settleCityCode' => 'require', // 结算信息城市代码
                'settleCityName' => 'require', // 结算信息城市名称
                'accountNo' => 'require', // 结算人银行卡号
                'accountName' => 'require', // 结算人账户名称
                'accountType' => 'require', // 结算账户类型
                'accountIdCard' => 'require', // 结算人证件号码
//                'attchments' => 'require', // 附件信息集合
                'settleType' => 'require', // 结算类型
//                'bizContent' => 'require', // 业务扩展信息

//                'agree_ment' => 'require',
                'bank_card' => 'require',
                'id_card_front' => 'require',
                'id_card_behind' => 'require',
                'shop_outside_img' => 'require',
                'shop_inside_img' => 'require',
                'business_licence' => 'require',
//                'opening_permit' => 'require',
                'checkstand_img' => 'require',
            ])->message([
                'merchantNo.require'  => 'merchantNo必须传递', // 商户号
                'appid.require'  => 'appid必须传递',
                'app_store_id.require'  => 'app_store_id必须传递',
                'app_type.require'  => 'app_type必须传递',
//                'store_name.require'  => 'store_name必须传递',
                'latitude.require'  => 'latitude必须传递',
                'longtude.require'  => 'longtude必须传递',
//                'userNo.require' => 'userNo必须传递',
//                'userNo.unique' => 'userNo必须唯一',
                'email.require' => 'email必须传递',
                'email.email' => 'email格式不正确',
//                'busiCode.require' => 'busiCode业务类型必须传递',
                'merRegName.require' => 'merRegName商户注册名称必须传递',
                'merType.require' => 'merType商户注册类型必须传递',
                'merType.in' => 'merType商户注册类型取值必须为TP_MERCHANT或TP_PERSONAL',
                'merName.require' => 'merName商户名称必须传递',
                'merAddr.require' => 'merAddr商户详细地址必须传递',
                'provinceCode.require' => 'provinceCode省代码必须传递',
                'cityCode.require' => 'cityCode市代码必须传递',
                'countyCode.require' => 'countyCode区县代码必须传递',
                'source.require' => 'source进件来源必须传递',
                'source.in' => 'source进件来源取值必须为APP或H5',
                'businessContent.require' => 'businessContent商户经营内容必须传递',
                'larName.require' => 'larName法人姓名必须传递',
                'larIdType.require' => 'larIdType法人证件类型必须传递',
                'larIdType.in' => 'larIdType法人证件类型取值必须为01,02,03,04,10,11,12,13,99之一',
                'larIdCard.require' => 'larIdCard法人证件号码必须传递',
                'larIdCardStart.require' => 'larIdCardStart法人证件开始日期必须传递',
                'larIdCardEnd.require' => 'larIdCardEnd法人证件过期时间必须传递',
                'contactMobile.require' => 'contactMobile商户联系人手机号码必须传递',
                'contactName.require' => 'contactName商户联系人姓名必须传递',
                'openningBankCode.require' => 'openningBankCode结算账户开户行号必须传递',
                'openningBankName.require' => 'openningBankName结算账户开户行名称必须传递',
                'clearingBankCode.require' => 'clearingBankCode结算账户清算行号必须传递',
                'settleProvinceCode.require' => 'settleProvinceCode结算信息省份代码必须传递',
                'settleProvinceName.require' => 'settleProvinceName结算信息省份名称必须传递',
                'settleCityCode.require' => 'settleCityCode结算信息城市代码必须传递',
                'settleCityName.require' => 'settleCityName结算信息城市名称必须传递',
                'accountNo.require' => 'accountNo结算人银行卡号必须传递',
                'accountName.require' => 'accountName结算人账户名称必须传递',
                'accountType.require' => 'accountType结算账户类型必须传递',
                'accountIdCard.require' => 'accountIdCard结算人证件号码必须传递',
//                'attchments.require' => 'attchments附件信息集合必须传递',
                'settleType.require' => 'settleType结算类型必须传递',
//                'bizContent.require' => 'bizContent业务扩展信息必须传递',
                'mcc.require' => 'mcc商户MCC编号必须传递',

                //                'agree_ment.require' => 'agree_ment入网协议必传',
                'bank_card.require' => 'bank_card银行卡号必传',
                'id_card_front.require' => 'id_card_front身份证正⾯必传',
                'id_card_behind.require' => 'id_card_behind身份证反⾯必传',
                'shop_outside_img.require' => 'shop_outside_img门头照片必传',
                'shop_inside_img.require' => 'shop_inside_img店铺内部照片必传',
                'business_licence.require' => 'business_licence营业执照照⽚必传',
//                'opening_permit.require' => 'opening_permit开户许可证必传',
                'checkstand_img.require' => 'checkstand_img收银台照片必传',

            ])->check($params);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        //查询商户号在支付平台是否存在
        $shop = Shop::where('merchantNo', $params['merchantNo'])->field('id')->find();
        if ( empty($shop) ) {
            return result_error('修改失败:商户号不存在');
        }
        $basic_res = $this->basicUpdate($params);
        if ( !$basic_res['success'] ) {
            return result_error('修改失败:'.$basic_res['msg']);
        }

        $settle_res = $this->settleUpdate($params);

        if ( !$settle_res['success'] ) {
            return result_error('修改失败:'.$settle_res['msg']);
        }

        return result_success('修改成功');
    }

    public function basicUpdate($params)
    {
        // 组装基本信息变更请求参数
        $basicUpdateData = [
            'customerNo' => $params['merchantNo'],
            'merBlis' => $params['licenseNo'] ?? '',
            'merBlisName' => $params['licenseName'] ?? '',
            'merBlisExpDt' => $params['licenseDtEnd'] ?? '',
            'merBizName' => $params['merName'] ?? '',
            'provinceCode' => $params['provinceCode'] ?? '',
            'cityCode' => $params['cityCode'] ?? '',
            'countyCode' => $params['countyCode'] ?? '',
            'merRegAddr' => $params['merAddr'] ?? '',
            'merContactName' => $params['contactName'] ?? '',
            'merContactMobile' => $params['contactMobile'] ?? '',
            'larName' => $params['larName'] ?? '',
            'larIdCard' => $params['larIdCard'] ?? '',
            'larIdCardStart' => $params['larIdCardStart'] ?? '',
            'larIdCardEnd' => $params['larIdCardEnd'] ?? '',
            'merType' => $params['merType'] ?? 'TP_PERSONAL',
        ];

        // 处理附件
        $basicAttachments = [];
        $basicSaveAttachmentData = [];
        $basicAttachmentTypes = [
            'agree_ment' => 'AGREE_MENT',
            'id_card_front' => 'ID_CARD_FRONT',
            'id_card_behind' => 'ID_CARD_BEHIND',
            'business_licence' => 'BUSINESS_LICENCE',
            'shop_outside_img' => 'SHOP_OUTSIDE_IMG',
            'shop_inside_img' => 'SHOP_INSIDE_IMG'
        ];

        foreach ($params as $key => $value) {
            if (isset($basicAttachmentTypes[$key]) && !empty($value)) {
                $basicAttachments[] = [
                    'imgPath' => $value,
                    'imgType' => $basicAttachmentTypes[$key]
                ];
                $basicSaveAttachmentData[$key] = $value;
            }
        }

        if (!empty($basicAttachments)) {
            $basicUpdateData['fileData'] = $basicAttachments;
        }

        // 如果是企业商户且需要变更注册名称
        if ($params['merType'] === 'TP_MERCHANT' && !empty($params['merRegName'])) {
            $basicUpdateData['merRegName'] = $params['merRegName'];
        }
        // 使用事务确保数据一致性
        try {
            $res = $this->ApiService->sendUpdateTokenUnite('merchant_basic_update', $basicUpdateData);

            if (empty($res['reviewRelatedId'])) {
                throw new \RuntimeException($res['message']);
            }
            $shop = Shop::where('merchantNo', $params['merchantNo'])->findOrFail();
            //更新成功 记录数据
            $basicSaveData = [
                'merchantNo' => $params['merchantNo'],
                'licenseNo' => $params['licenseNo'] ?? '',
                'licenseName' => $params['licenseName'] ?? '',
                'licenseDtEnd' => $params['licenseDtEnd'] ?? '',
                'merName' => $params['merName'] ?? '',
                'provinceCode' => $params['provinceCode'] ?? '',
                'provinceName' =>  $params['provinceName'] ?? '',
                'cityCode' => $params['cityCode'] ?? '',
                'countyCode' => $params['countyCode'] ?? '',
                'merAddr' => $params['merAddr'] ?? '',
                'contactName' => $params['contactName'] ?? '',
                'contactMobile' => $params['contactMobile'] ?? '',
                'larName' => $params['larName'] ?? '',
                'larIdCard' => $params['larIdCard'] ?? '',
                'larIdcardStDt' => $params['larIdCardStart'] ?? '',
                'larIdcardExpDt' => $params['larIdCardEnd'] ?? '',
                'channelType' => $params['merType'] ?? 'TP_PERSONAL',
            ];
            $basicSaveData = array_merge($basicSaveData,$basicSaveAttachmentData);

            $shop->save($basicSaveData);

            return [
                'success'=>true,
                'msg'=>''
            ];
        } catch (\Exception $e) {
            Log::error('商户基础信息更新失败: '.$e->getMessage());
            return [
                'success'=>false,
                'msg'=>$res['message']
            ];
        }
    }

    //结算信息修改
    public function settleUpdate($params)
    {
        // 组装结算信息变更请求参数
        $settleUpdateData = [
            'customerNo' => $params['merchantNo'],
            'accountKind' => $params['accountType'] ?? '58',
            'accountName' => $params['accountName'] ?? '',
            'accountNo' => $params['accountNo'] ?? '',
            'bankName' => $params['openningBankName'] ?? '',
            'bankNo' => $params['openningBankCode'] ?? '',
            'clearingBankNo' => $params['clearingBankCode'] ?? '',
            'identityNo' => $params['accountIdCard'] ?? $params['larIdCard'] ?? '',
            'isLegalPerson' => (bool)($params['isLegalPerson'] ?? true),
            'settleProvinceCode' => $params['settleProvinceCode'] ?? '',
            'settleProvinceName' => $params['settleProvinceName'] ?? '',
            'settleCityCode' => $params['settleCityCode'] ?? '',
            'settleCityName' => $params['settleCityName'] ?? '',
        ];

        // 处理结算附件
        $settleAttachments = [];
        $settleSaveAttachmentData = [];
        $settleAttachmentTypes = [
            'bank_card' => 'BANK_CARD',
            'settle_id_card_front' => 'SETTLE_ID_CARD_FRONT',
            'settle_id_card_behind' => 'SETTLE_ID_CARD_BEHIND',
            'opening_permit' => 'OPENING_PERMIT'
        ];

        foreach ($params as $key => $value) {
            if (isset($settleAttachmentTypes[$key]) && !empty($value)) {
                $settleAttachments[] = [
                    'imgPath' => $value,
                    'imgType' => $settleAttachmentTypes[$key]
                ];
                $settleSaveAttachmentData[$key] = $value;
            }
        }

        if (!empty($settleAttachments)) {
            $settleUpdateData['attachments'] = $settleAttachments;
        }
        // 使用事务确保数据一致性

        try {
            //调用结算更新接口
            $res = $this->ApiService->sendUpdateTokenUnite('merchant_settle_update',$settleUpdateData);

            if (empty($res['reviewRelatedId'])) {
                throw new \RuntimeException($res['message']);
            }
            $shop = Shop::where('merchantNo', $params['merchantNo'])->findOrFail();
            //更新成功 记录数据
            $settleSaveData = [
                'merchantNo' => $params['merchantNo'],
                'accountType' => $params['accountType'] ?? '58',
                'accountName' => $params['accountName'] ?? '',
                'accountNo' => $params['accountNo'] ?? '',
                'openningBankName' => $params['openningBankName'] ?? '',
                'openningBankCode' => $params['openningBankCode'] ?? '',
                'clearingBankCode' => $params['clearingBankCode'] ?? '',
                'accountIdCard' => $params['accountIdCard'] ?? $params['larIdCard'] ?? '',
                'isLegalPerson' => (bool)($params['isLegalPerson'] ?? true),
                'settleProvinceCode' => $params['settleProvinceCode'] ?? '',
                'settleProvinceName' => $params['settleProvinceName'] ?? '',
                'settleCityCode' => $params['settleCityCode'] ?? '',
                'settleCityName' => $params['settleCityName'] ?? '',
            ];
            $basicSaveData = array_merge($settleSaveData,$settleSaveAttachmentData);

            $shop->save($basicSaveData);

            return [
                'success'=>true,
                'msg'=>''
            ];
        } catch (\Exception $e) {
            Log::error('商户基础信息更新失败: '.$e->getMessage());
            return [
                'success'=>false,
                'msg'=>$res['message']
            ];
        }

    }

    /**
     * 商户详情
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function merchant_info($params=[])
    {
        // 验证数据
        try {
            validate([
                'appid'  => 'require', // 应用ID
//                'app_store_id'  => 'require', // 商户ID
                'app_type'  => 'require', // 应用类型
                'merchantNo'  => 'require',
            ])->check($params);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        //查询商户号在支付平台是否存在
        $shop = Shop::where('merchantNo', $params['merchantNo'])->find();
        if ( empty($shop) ) {
            return result_error('查询失败:商户号不存在');
        }

        $data['customerNo'] = $params['merchantNo']??'';// 商户号

        $decode_data = $this->sendEncryptedRequest('merchant_info', $data);

        if (empty($decode_data)) {
            return result_error('查询失败');
        }
        //可获取外部商户号/ 终端设备号(支付用)
//            $decode_data['customer']['externalCustomerNo'] //外部商户号
        //$decode_data['customer']['shopInfoList']['shopId'] //网点编号  (增终使用)
        //$decode_data['customer']['terminalInfo']['activeNoVoList'][0]['termNo']  //终端设备号
        //$decode_data['customer']['terminalInfo']['termNoList'][0]  //终端设备号

        if ( empty($shop->externalCustomerNo) ) {
            $shop->externalCustomerNo = $decode_data['customer']['externalCustomerNo'];
            $shop->save();
        }
        return result_success('success',$decode_data);
        ///

/*        $privateKey=env('lakala.push_private_key');

        $str = json_encode($data);

        $encode_data =  $this->ApiService->privateKeyDecrypt($str,$privateKey);

        $res = $this->ApiService->sendTokenUnite('merchant_info',['data'=>$encode_data]);

//        $res = '{"code":"000000","data":"X34tIzhfuCbJhOR6QKnRbgAKEfinuY2vjxVEca9t\/IwPo8Bqc7I9JI95PJ2xvf6pWdQGnx6bTilbil17SCLwXeyzOfN\/FsKm2ifhqaKSA3TT5HPrLEnAatBa1RlIpcVo\/xE3DfHLG16tO0pzEODQWrzdf97gCZkV727Wz6cE9cw37S\/nu4U3zVUUXC9eiQRvsHQkCNM+7scpGJ4tAZa713dbLHTV+95QXJUoEIKh4uaTeFU34+6EF6rfgAKNmwt1IJJkmgEpy0ZgRFVTnjUpwXEmNar7eUWuo8gqHBhBhlUjwOkV2BHQxDDRfa+CMGRNG4UWkoxpwSenwSw5JtMQwmmTbyocsGhQhpHzwj2Ntg8lA2QFJOtVPOq8IuJT38\/9EVl07\/qj0GzIxQJbj7\/VPMv7HoMIZgcGKPJd8ddB+haHD2CN1b9\/Li62eS3KGDsTussW5glNPgWV+RyqXtB7nVq6WF\/qib9jOxDoGtmv5zFa2Wojy2g5DwkWh\/HR2+udRktRwVjCxJGlJ8qfrP026A+pyVKk4FDuGzgoTzsfzA5m0l5hFmYa65oAijhQ3rWVNlI72rZeb9644XWmXR0XddvmBemx\/GcK4h3rjobaBov1SoQl7tbqi647v2mYFsQEUCYV\/PIjZYaWRvojTmzDp+2o\/pAy4YfWoQlZSoUSpn1nVXreObvypsEqHN3LspSYy0ZpfKqeXoJXkcE4mI+86TLgiBoUIzUADSkwIHxWwWMD1exU+Qnf56jw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pkcyHN4lY+aw+6hxu2Gh4+RWEsW\/cPSA2","message":"SUCCESS","timestamp":1752737902669}';
//        $res = json_decode($res,true);

        if ( isset($res['code']) && $res['code']=='000000') {
                $publicKey = env('lakala.push_public_key');
                $decode_data =  $this->ApiService->publicKeyDecrypt($res['data'],$publicKey);
                //{"customer":{"activeNo":"689359915828","activityType":"H_W_PAY","activityTypeName":"汇拓客专业化扫码活动","agencyNo":30000081,"agentNo":20000101,"agreementStatus":"TRUE","bzPos":"WECHAT_PAY","channelType":"TP_MERCHANT","cityName":"柳州市","contactManName":"徐**","countyName":"柳州市","createTime":1752304632000,"customerName":"烟酒行批发24小时","customerNo":100141021,"customerStatus":"OPEN","externalCustomerNo":"8226140581200D5","identityNo":"460027********7612","identityNoExpire":"2035-01-16","identityNoStDt":"2015-01-16","isStandard":"FALSE","legalName":"徐**","licenseNo":"92450202MA5MWYQK31","mailbox":"28***9@qq.com","mccCode":"5812","merLicenseExpire":"9999-12-31","merLicenseStDt":"2017-11-21","merName":"烟酒行批发24小时","merRegName":"烟酒行批发24小时","merchantSource":"H5","openTime":1752304641000,"optimistic":14,"phoneNo":"182******50","phoneNoEnc":"ANGG3XpIONCkA7G/e3o2AA==","phoneNoHash":"f3ad8f451f3850f288656b93e746ae2a","platform":"LKL","posSn":"","provinceName":"广西自治区","receiveDetail":"柳州市解放南路金鱼巷1号花旗壹号楼15-10","rewardMode":"TO_AGENT","standardFee":0.0,"termNo":"D9359915","termNum":1,"updateTime":1752733817000,"ysfDiscount":"FALSE"},"customerFee":[{"cardApplicationId":17043401,"cardType":"DEBIT_CARD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":300000.0,"feeRate":0.0038,"id":113825924,"maxAmt":20.0,"minAmt":0.1,"monthLimit":3000000.0,"optimistic":0,"perLimi":100000.0,"termId":11240090,"transSettleType":"D1","transType":"POS"},{"cardApplicationId":17043401,"cardType":"CREDIT_CARD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":300000.0,"feeRate":0.006,"id":113825925,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":3000000.0,"optimistic":0,"perLimi":50000.0,"termId":11240090,"transSettleType":"D1","transType":"POS"},{"cardApplicationId":17043402,"cardType":"WECHAT","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825926,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"ALIPAY","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825927,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"QR_CORD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825928,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"UNIONPAY_WALLET_DEBIT_FEE","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825929,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"UNIONPAY_WALLET_CREDIT_FEE","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825930,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000}],"productVos":[{"product":"WECHAT_PAY","productName":"专业化扫码"}],"settleCard":{"ableStatus":"ENABLE","accountKind":"58","accountName":"徐**","accountNo":"6228****6714","auditStatus":"SUCCESS","bankCode":"01030000","bankName":"中国农业银行广西柳州市柳南支行营业室","bankNo":"103614010818","cityCode":"6140","cityName":"柳州市","clearingBankNo":"103100000026","createTime":1752304633000,"id":33901,"idCard":"4****************2","isLegalPerson":true,"optimistic":4,"ownNo":"100141021","provinceCode":"45","provinceName":"广西","updateTime":1752733818000},"shopInfoList":[{"cityCode":"6140","cityName":"柳州市","provinceCode":"6100","provinceName":"广西自治区","shopAddress":"柳州市解放南路金鱼巷1号花旗壹号楼15-10","shopContactMobile":"182******50","shopContactName":"徐**","shopDistCode":"986140","shopDistName":"柳州市","shopId":34011,"shopName":"烟酒行批发24小时"}],"terminalInfo":[{"activeNoVoList":[{"activeNo":"689359915828","busiTypeCode":"QR_CODE_CARD","termNo":"D9359915"}],"coreTermId":996434868585103360,"termNoList":["D9359915"],"termTypeCode":106,"termTypeName":"专业化扫码"}]}
            $decode_data = json_decode($decode_data,true);

            //可获取外部商户号/ 终端设备号(支付用)
//            $decode_data['customer']['externalCustomerNo'] //外部商户号
            //$decode_data['customer']['shopInfoList']['shopId'] //网点编号  (增终使用)
            //$decode_data['customer']['terminalInfo']['activeNoVoList'][0]['termNo']  //终端设备号
            //$decode_data['customer']['terminalInfo']['termNoList'][0]  //终端设备号

            if ( empty($shop->externalCustomerNo) ) {
                $shop->externalCustomerNo = $decode_data['customer']['externalCustomerNo'];
                $shop->save();
            }

            return result_success('success',$decode_data);

        }
        return result_error('查询失败');*/


    }

    /**
     * 增终进件
     * @param $params
     * @return array
     */
    public function addTerm($params=[])
    {
        try {
            validate([
                'appid'  => 'require', // 应用ID
                'app_type'  => 'require', // 应用类型
                'externalCustomerNo'  => 'require', // 外部商户号
                'shopId' => 'require', //网点编号
            ])->check($params);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }
        $data = [
            'externalCustomerNo' => $params['externalCustomerNo'], //外部商户号
            'bzPos' => 'WECHAT_PAY', //POS类型  WECHAT_PAY 专业化扫码
            'termNum' => 1,  //终端数量
            'shopId' => $params['shopId'],  //网点编号 (商户信息接口中返回 shopInfoList.shopId)
        ];
        $decode_data = $this->sendEncryptedRequest('addTerm', $data);

        if (empty($decode_data)) {
            return result_error('查询失败');
        }
        if ( isset($decode_data['reviewRelatedId']) && $decode_data['reviewRelatedId'] ) {
            return result_success('success',$decode_data);
        }
        return result_error('请求失败');

/*        $privateKey=env('lakala.push_private_key');

        $str = json_encode($data);

        $encode_data =  $this->ApiService->privateKeyDecrypt($str,$privateKey);

//        $res = $this->ApiService->sendTokenUnite('addTerm',['data'=>$encode_data]);
        $res = '{"code":"000000","data":"qdMsDTvmrRTElh37QksrL1Xft71tXBo3tmIutwJxbKwN4T76I7EWAVsGJOr2XqUmuyF9ZgczChyg3j228d2\/lsGKRO+lVoJqy7nkJ09Z2RsDi0MX3AeF3l9SSFXvBiyyjPwqKAS7n+VuZaW9EdB2+h2jTP\/SV1z6nBUQP5GNvTA=","message":"SUCCESS","timestamp":1752743288570}';
        $res = json_decode($res,true);
        if ( isset($res['code']) && $res['code']=='000000') {
            $publicKey = env('lakala.push_public_key');
            $decode_data =  $this->ApiService->publicKeyDecrypt($res['data'],$publicKey);
            //{"customer":{"activeNo":"689359915828","activityType":"H_W_PAY","activityTypeName":"汇拓客专业化扫码活动","agencyNo":30000081,"agentNo":20000101,"agreementStatus":"TRUE","bzPos":"WECHAT_PAY","channelType":"TP_MERCHANT","cityName":"柳州市","contactManName":"徐**","countyName":"柳州市","createTime":1752304632000,"customerName":"烟酒行批发24小时","customerNo":100141021,"customerStatus":"OPEN","externalCustomerNo":"8226140581200D5","identityNo":"460027********7612","identityNoExpire":"2035-01-16","identityNoStDt":"2015-01-16","isStandard":"FALSE","legalName":"徐**","licenseNo":"92450202MA5MWYQK31","mailbox":"28***9@qq.com","mccCode":"5812","merLicenseExpire":"9999-12-31","merLicenseStDt":"2017-11-21","merName":"烟酒行批发24小时","merRegName":"烟酒行批发24小时","merchantSource":"H5","openTime":1752304641000,"optimistic":14,"phoneNo":"182******50","phoneNoEnc":"ANGG3XpIONCkA7G/e3o2AA==","phoneNoHash":"f3ad8f451f3850f288656b93e746ae2a","platform":"LKL","posSn":"","provinceName":"广西自治区","receiveDetail":"柳州市解放南路金鱼巷1号花旗壹号楼15-10","rewardMode":"TO_AGENT","standardFee":0.0,"termNo":"D9359915","termNum":1,"updateTime":1752733817000,"ysfDiscount":"FALSE"},"customerFee":[{"cardApplicationId":17043401,"cardType":"DEBIT_CARD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":300000.0,"feeRate":0.0038,"id":113825924,"maxAmt":20.0,"minAmt":0.1,"monthLimit":3000000.0,"optimistic":0,"perLimi":100000.0,"termId":11240090,"transSettleType":"D1","transType":"POS"},{"cardApplicationId":17043401,"cardType":"CREDIT_CARD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":300000.0,"feeRate":0.006,"id":113825925,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":3000000.0,"optimistic":0,"perLimi":50000.0,"termId":11240090,"transSettleType":"D1","transType":"POS"},{"cardApplicationId":17043402,"cardType":"WECHAT","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825926,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"ALIPAY","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825927,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"QR_CORD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825928,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"UNIONPAY_WALLET_DEBIT_FEE","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825929,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"UNIONPAY_WALLET_CREDIT_FEE","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825930,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000}],"productVos":[{"product":"WECHAT_PAY","productName":"专业化扫码"}],"settleCard":{"ableStatus":"ENABLE","accountKind":"58","accountName":"徐**","accountNo":"6228****6714","auditStatus":"SUCCESS","bankCode":"01030000","bankName":"中国农业银行广西柳州市柳南支行营业室","bankNo":"103614010818","cityCode":"6140","cityName":"柳州市","clearingBankNo":"103100000026","createTime":1752304633000,"id":33901,"idCard":"4****************2","isLegalPerson":true,"optimistic":4,"ownNo":"100141021","provinceCode":"45","provinceName":"广西","updateTime":1752733818000},"shopInfoList":[{"cityCode":"6140","cityName":"柳州市","provinceCode":"6100","provinceName":"广西自治区","shopAddress":"柳州市解放南路金鱼巷1号花旗壹号楼15-10","shopContactMobile":"182******50","shopContactName":"徐**","shopDistCode":"986140","shopDistName":"柳州市","shopId":34011,"shopName":"烟酒行批发24小时"}],"terminalInfo":[{"activeNoVoList":[{"activeNo":"689359915828","busiTypeCode":"QR_CODE_CARD","termNo":"D9359915"}],"coreTermId":996434868585103360,"termNoList":["D9359915"],"termTypeCode":106,"termTypeName":"专业化扫码"}]}
            $decode_data = json_decode($decode_data,true);

            if ( isset($decode_data['reviewRelatedId']) && $decode_data['reviewRelatedId'] ) {
                return result_success('success',$decode_data);
            }
            return result_error('请求失败');
        }
        return result_error('请求失败');*/

    }

    /**
     * 获取已绑定终端信息
     * @param $params
     * @return array
     */
    public function microTermList($params=[])
    {
        try {
            validate([
                'appid'  => 'require', // 应用ID
                'app_type'  => 'require', // 应用类型
                'externalCustomerNo'  => 'require', // 外部商户号
            ])->check($params);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        $data = [
            'externalCustomerNo' => $params['externalCustomerNo'], //外部商户号
        ];
        $decode_data = $this->sendEncryptedRequest('microTermList', $data);

        if (empty($decode_data)) {
            return result_error('查询失败');
        }
        return result_success('success',$decode_data);
        //
/*        $privateKey=env('lakala.push_private_key');
        $str = json_encode($data);
        $encode_data =  $this->ApiService->privateKeyDecrypt($str,$privateKey);
        $res = $this->ApiService->sendTokenUnite('microTermList',['data'=>$encode_data]);
//        $res = '{"code":"000000","data":"kbnLfl52\/qJDK45ctiVC3HMGrec0vGneG1ShQGBuCnM9CkcUO\/ByYQnxLoeD8S5g3zl0+UJHrbCcCAIU3cEbZq+Q9dcRdjb+4JENVpZXuPiySQHsBgC96iKPTCj3lRZIA7VPLHH37AoI8HHnMXkuxwTFFoODJNYp8Wr8kClnn4c=","message":"SUCCESS","timestamp":1752747331136}';
//        $res = json_decode($res,true);
        if ( isset($res['code']) && $res['code']=='000000') {
            $publicKey = env('lakala.push_public_key');

            $decode_data =  $this->ApiService->publicKeyDecrypt($res['data'],$publicKey);
            //{"customer":{"activeNo":"689359915828","activityType":"H_W_PAY","activityTypeName":"汇拓客专业化扫码活动","agencyNo":30000081,"agentNo":20000101,"agreementStatus":"TRUE","bzPos":"WECHAT_PAY","channelType":"TP_MERCHANT","cityName":"柳州市","contactManName":"徐**","countyName":"柳州市","createTime":1752304632000,"customerName":"烟酒行批发24小时","customerNo":100141021,"customerStatus":"OPEN","externalCustomerNo":"8226140581200D5","identityNo":"460027********7612","identityNoExpire":"2035-01-16","identityNoStDt":"2015-01-16","isStandard":"FALSE","legalName":"徐**","licenseNo":"92450202MA5MWYQK31","mailbox":"28***9@qq.com","mccCode":"5812","merLicenseExpire":"9999-12-31","merLicenseStDt":"2017-11-21","merName":"烟酒行批发24小时","merRegName":"烟酒行批发24小时","merchantSource":"H5","openTime":1752304641000,"optimistic":14,"phoneNo":"182******50","phoneNoEnc":"ANGG3XpIONCkA7G/e3o2AA==","phoneNoHash":"f3ad8f451f3850f288656b93e746ae2a","platform":"LKL","posSn":"","provinceName":"广西自治区","receiveDetail":"柳州市解放南路金鱼巷1号花旗壹号楼15-10","rewardMode":"TO_AGENT","standardFee":0.0,"termNo":"D9359915","termNum":1,"updateTime":1752733817000,"ysfDiscount":"FALSE"},"customerFee":[{"cardApplicationId":17043401,"cardType":"DEBIT_CARD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":300000.0,"feeRate":0.0038,"id":113825924,"maxAmt":20.0,"minAmt":0.1,"monthLimit":3000000.0,"optimistic":0,"perLimi":100000.0,"termId":11240090,"transSettleType":"D1","transType":"POS"},{"cardApplicationId":17043401,"cardType":"CREDIT_CARD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":300000.0,"feeRate":0.006,"id":113825925,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":3000000.0,"optimistic":0,"perLimi":50000.0,"termId":11240090,"transSettleType":"D1","transType":"POS"},{"cardApplicationId":17043402,"cardType":"WECHAT","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825926,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"ALIPAY","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825927,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"QR_CORD","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825928,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"UNIONPAY_WALLET_DEBIT_FEE","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825929,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000},{"cardApplicationId":17043402,"cardType":"UNIONPAY_WALLET_CREDIT_FEE","createTime":1752304633000,"customerManagementFee":0.0,"customerManagementdFee":0.0,"customerManagementeFee":0.0,"customerManagementfFee":0.0,"customerNo":100141021,"dayLimit":10000.0,"feeRate":0.006,"id":113825930,"maxAmt":9999.0,"minAmt":0.1,"monthLimit":200000.0,"optimistic":1,"perLimi":5000.0,"termId":11240090,"termNo":"D9359915","transSettleType":"D1","transType":"SCAN","updateTime":1752304641000}],"productVos":[{"product":"WECHAT_PAY","productName":"专业化扫码"}],"settleCard":{"ableStatus":"ENABLE","accountKind":"58","accountName":"徐**","accountNo":"6228****6714","auditStatus":"SUCCESS","bankCode":"01030000","bankName":"中国农业银行广西柳州市柳南支行营业室","bankNo":"103614010818","cityCode":"6140","cityName":"柳州市","clearingBankNo":"103100000026","createTime":1752304633000,"id":33901,"idCard":"4****************2","isLegalPerson":true,"optimistic":4,"ownNo":"100141021","provinceCode":"45","provinceName":"广西","updateTime":1752733818000},"shopInfoList":[{"cityCode":"6140","cityName":"柳州市","provinceCode":"6100","provinceName":"广西自治区","shopAddress":"柳州市解放南路金鱼巷1号花旗壹号楼15-10","shopContactMobile":"182******50","shopContactName":"徐**","shopDistCode":"986140","shopDistName":"柳州市","shopId":34011,"shopName":"烟酒行批发24小时"}],"terminalInfo":[{"activeNoVoList":[{"activeNo":"689359915828","busiTypeCode":"QR_CODE_CARD","termNo":"D9359915"}],"coreTermId":996434868585103360,"termNoList":["D9359915"],"termTypeCode":106,"termTypeName":"专业化扫码"}]}
            $decode_data = json_decode($decode_data,true);
//            if ( isset($decode_data['reviewRelatedId']) && $decode_data['reviewRelatedId'] ) {
                return result_success('success',$decode_data);
//            }
//            return result_error('请求失败');
        }
        return result_error('请求失败');*/
    }

    /**
     * 查询支付宝微信子商户
     * @param $params
     * @return array
     */
    public function subMerchantQuery($params=[])
    {
        try {
            validate([
                'appid'  => 'require', // 应用ID
                'app_type'  => 'require', // 应用类型
                'externalCustomerNo'  => 'require', // 外部商户号
            ])->check($params);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        $data = [
            'externalCustomerNo' => $params['externalCustomerNo'], //外部商户号
        ];

        $decode_data = $this->sendEncryptedRequest('subMerchantQuery', $data);

        if (empty($decode_data)) {
            return result_error('查询失败');
        }
        return result_success('success',$decode_data);

    }

    public function ec_apply($params=[])
    {

        // 验证必填参数  字段更改为支付平台字段  请求时转换
        try {
            validate([
                'appid'  => 'require', // 应用ID
                'app_type'  => 'require', // 应用类型

//                'order_no'  => 'require', // 请求单号 支付平台生成
//                'org_id'  => 'require', // 机构号 支付平台生成
//                'ec_type_code'  => 'require', //	合同类别  默认值EC007
                'larIdType' => 'require|in:01,02,03,04', // 法人证件类型 cert_type
                'larName' => 'require', // 法人/经营者姓名  cert_name
                'larIdCard' => 'require', // 法人/经营者证件号码 cert_no
                'mobile'  => 'require', // 签约手机号 法人        mobile
                'licenseNo' => 'require', //营业执照号           business_license_no
                'licenseName' => 'require', //营业执照名称        business_license_name
                'openningBankCode' => 'require', //结算开户行号   openning_bank_code
                'openningBankName' => 'require', //结算开户行名称 openning_bank_name
                'accountType' => 'require|in:57,58', //结算卡性质 57 对公、 58 对私   acct_type_code
                'accountNo' => 'require', //结算卡号             acct_no
                'accountName' => 'require', //结算卡名称          acct_name
                'ret_url' => 'require', //调用平台回调地址         ret_url

//                'ec_content_parameters' => 'require', //电子合同内容参数集合
                 //下面是参数合集必填参数 start
//                'licenseName' => 'require', //营业执照名称 A1
                'businessContent' => 'require', //营业执照经营内容
                'email' => 'require|email', //邮箱
                'merAddr' => 'require', //营业执照地址
                'licenseDtStart' => 'require', //营业执照注册日期

                //授权和结算授权暂时不考虑,
                //下面是参数合集必填参数 end
            ])->check($params);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

//        // 如果启用经办人，验证相关字段
//        if (!empty($params['agent_tag']) && $params['agent_tag'] == 1) {
//            $agentFields = ['agent_name', 'agent_cert_type', 'agent_cert_no'];
//            foreach ($agentFields as $field) {
//                if (empty($params[$field])) {
//                    return [
//                        'code' => 'PARAM_MISSING',
//                        'message' => "启用经办人时，{$field}为必填",
//                        'data' => null
//                    ];
//                }
//            }
//        }

        $larIdTypeMap = [
            '01'=>'RESIDENT_ID',
            '02'=>'PASSPORT',
            '03'=>'HK_MACAO_PASS',
            '04'=>'TAIWAN_PASS'
        ];

        $dateParts = explode('-', $params['licenseDtStart']);
        $licenseYear = $dateParts[0];
        $licenseMonth = $dateParts[1];
        $date = date('Y-m-d');
        $data = [
            'order_no'  => get_order_num(1), // 请求单号 支付平台生成
            'org_id'  =>  $this->config['org_id'],   //测试环境传1
            'ec_type_code' => 'EC007', //	合同类别  默认值EC007
            'cert_type' => $larIdTypeMap[$params['larIdType']],
            'cert_name' => $params['larName'],
            'cert_no' => $params['larIdCard'],
            'mobile' => $params['mobile'],
            'business_license_no' => $params['licenseNo'],
            'business_license_name' => $params['licenseName'],
            'openning_bank_code' => $params['openningBankCode'],
            'openning_bank_name' => '中国建设银行', // $params['openningBankName']
            'acct_type_code' => (int)$params['accountType'],
            'acct_no' => $params['accountNo'],
            'acct_name' => $params['accountName'],
            'agent_tag' => 0,
            'ret_url' => $this->config['ec_notify_url'], //回调地址使用支付平台地址
//            'ec_content_parameters' => []
            'ec_content_parameters' => [
                'A1' => $params['licenseName'], //营业执照名称
                'A2' => '是', //业务功能:消费类
                'A6' => '是', //收单手续费标准:银联借记卡
                'A7' => 0.38, //收单手续费标准:银联借记卡费率
                'A8' => 20,//收单手续费标准:银联借记卡封顶值
                'A9' => '是',//收单手续费标准:银联贷记卡
                "A10"=> 0.6, //收单手续费标准:银联贷记卡费率
                "A29"=> 0.38, //扫码支付业务:支付宝收单手续费率
                "A30"=> 0.38, //扫码支付业务:微信单手续费率
                "A31"=> 0.38, //扫码支付业务:京东收单手续费率
                "A32"=> 0.38, //扫码支付业务:拉卡拉钱包收单手续费率

                'A96' => 2, //结算方式D1
                'A97' => '是', //退货业务:开通
                "A100"=> '是', //数字人民币业务:不开通
                "A101"=> '中国境内', //终端使用地区
                "A102"=> '浙江鲸禧智创数字科技有限公司',//委托合作方的名称
//                "A103"=> '', //委托合作方平台
                'A104' => date('Y'), //甲方签约的年
                'A105' => date('m'), //甲方签约的月
                'A106' => date('d'), //甲方签约的日
                'A107' => date('Y'), //乙方签约的年
                'A108' => date('m'), //乙方签约的月
                'A109' => date('d'), //乙方签约的日
                'B1' =>  $licenseYear, //商户注册登记表的年
                'B2' =>  $licenseMonth, //商户注册登记表的月
                'B3' => '是',//商户注册登记表登记类型增商选择
                'B8'=> $params['licenseName'],
                'B9' =>  $params['businessContent'], //主营业务
                'B10' =>  $params['licenseName'], //商户对外经营名称(中英文)

                'B13' =>  $params['merAddr'], //办公地址
                'B14' =>  $params['licenseNo'], //营业执照注册号
                'B16' =>  $params['accountType'] == 57 ? '是' : '', //结算账户名称:同工商注册名称选择 TODO 对公结算勾选
                'B17' =>  $params['accountType'] == 58 ? '是' : '', //结算账户名称:其他名称选择     TODO 对私结算勾选
                'B18' =>  $params['accountType'] == 58 ? $params['accountName'] : '', //结算账户名称:其他名称填写     TODO 对私结算填写
                'B19' =>  $params['openningBankName'],//开户行(含支行)
                'B20' =>  $params['accountNo'],//结算账号
                'B24' =>  $params['larName'],//法人姓名
                'B25' =>  $params['larIdCard'],//法人证件号码
                'B26' =>  $params['mobile'],//法人手机
                'B27' =>  $params['larName'],//联系人姓名
                'B28' =>  $params['email'],//联系人邮箱
                'B29' =>  $params['larIdCard'],//联系人身份证号
                'B30' =>  $params['mobile'],//联系人手机号
                'B31' =>  $params['licenseName'],//分店营业名称
                'B32' =>  $params['larName'],//网点联系人姓名
                'B33' =>  $params['merAddr'],//终端布放地址
                'B34' =>  $params['mobile'],//网点联系人手机
                'B46' => "是",
                'B47' => "专业化扫码支付",
                'C1' => $params['larName'],//

                "C2"=> "100%",
                "C3"=> $params['larIdCard'],
                "C4"=> $params['larIdCardEnd'],
//                "C5"=> "山东省东阿县姜楼镇东寺村36号",//居住地址/工作地址/户籍地址
                "C6"=> "是",

                'D1' => $params['openningBankName'], //授权书(银行):结算账户所属银行全称
                'D2' => $date,   //授权书(银行):签章日期
                'D4' => '浙江鲸禧智创数字科技有限公司',//授权书(数据处理方):获得授权的数据服务公司名称
                "D5" => '13388664777',//授权书(数据处理方):获得授权的数据服务公司联系方式
                "D7" => $date, //授权书(数据处理方):签章日期
                "D9" => $date, //授权书(外卡业务):签章日期
                "D11" => $date, //授权书(开通微信、支付宝收单):签章目期
                "D12" => $date, //电子签约授权委托书;签章日期
//                "E1" => '', //结算授权委托书:授权公司名称
                "E2" => '特约商户分账协议', //结算授权委托书:与合作方签署协议名称
                "E3" => 1, //结算授权委托书:清分结算方式选择
                "E4" => 80, //结算授权委托书:商户分得最低分账比例
                "E7" => $date,//结算授权委托书:签章日期
            ]
        ];

        $save_data = $data;
        $save_data['ret_url'] = $params['ret_url'];
        $save_data['app_type'] = $params['app_type'];
        $save_data['appid'] = $params['appid'];
        //保存到表中
        $ecApplyModel = new LakalaEcApply();

        $ecApply = $ecApplyModel->create($save_data);

        $data['ec_content_parameters'] = json_encode($data['ec_content_parameters'],JSON_UNESCAPED_UNICODE);

        $res = $this->ApiService->sendV3Unite('ecApply',$data);

//        $res_json = '{"code":"000000","msg":"成功","resp_data":{"order_no":"e0a1d6f8dbca4ee99dddf8a805778d37","ec_apply_id":863797013367664640,"result_url":"https://jrt.wsmsd.cn/signature/s/wl6392"}}';
//        $res = json_decode($res_json,true);
//dd($res);
        if ( isset($res['code']) && $res['code'] == '000000' ) {
           //请求成功 记录请求单号   返回结果给调用平台
            $ecApply->ec_apply_id = $res['resp_data']['ec_apply_id'];
            $ecApply->api_response = $res;
            $ecApply->result_url =  $res['resp_data']['result_url'];
            $ecApply->save();
            return result_success('success',$res["resp_data"]);
        }

        return result_error($res["msg"]??'请求失败');

    }

    public function ec_query($params=[])
    {
        try {
            validate([
                'appid'  => 'require', // 应用ID
                'app_type'  => 'require', // 应用类型
                'ec_apply_id' => 'require', // ec申请id

            ])->check($params);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }
        //先查询本地是否 存在 或者 已经通过
        $ecApply = LakalaEcApply::where('appid',$params['appid'])
            ->where('ec_apply_id',$params['ec_apply_id'])
            ->find();

        if ( empty($ecApply) ) {
            return result_error('未找到记录');
        }
        if ( $ecApply->status == LakalaEcApply::STATUS_COMPLETED && !empty($ecApply->ec_no)) {
            return result_success('success',[
                'status'=>$ecApply->status,
                'ec_apply_id'=>$ecApply->ec_apply_id,
                'ec_no'=>$ecApply->ec_no,
                'status_str'=>'已完成'
                ]);
        }

        $data = [
            'order_no'  => get_order_num(1), // 请求单号 支付平台生成
            'org_code'  =>  $this->config['org_id'],   //测试环境传1
            'ec_apply_id'  => $params['ec_apply_id'],
            'version' => '1.0'
        ];
        $res = $this->ApiService->sendV3Unite('ecQuery',$data);

        if ( isset($res['code']) && $res['code'] == '000000' ) {
            $ec_status = $res['resp_data']['ec_status'];
            //更新表数据下状态
            $ecApply->status  = LakalaEcApply::getEcStatus($ec_status);
            $ecApply->ec_no = $res['resp_data']['ec_no'];
            $ecApply->save();

            return result_success('success',[
                'status'=>$ecApply->status,
                'ec_apply_id'=>$ecApply->ec_apply_id,
                'ec_no'=>$ecApply->ec_no,
                'status_str'=>LakalaEcApply::getEcStatusStr($ec_status)
                ]);
        }

        return result_error('查询失败:'.$res['msg']);


    }

    // 获取地区信息get请求
    public function areaInfo($params=[])
    {
        try {
            validate([
                'parentCode'  => 'require', 
            ])->message([
                'parentCode.require'  => 'parentCode必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['parentCode']=$params['parentCode']??1;

        $res = $this->ApiService->sendTokenUnite('areaInfo',$data,'get');

        return $this->ApiService->returnTokenUnite($res);
    }

    // 获取银行地区信息get请求
    public function bankAreaInfo($params=[])
    {
        try {
            validate([
                'parentCode'  => 'require', 
            ])->message([
                'parentCode.require'  => 'parentCode必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['parentCode']=$params['parentCode']??1;

        $res = $this->ApiService->sendTokenUnite('bankAreaInfo',$data,'get');

        return $this->ApiService->returnTokenUnite($res);
    }

    // 获取银行列表信息get请求
    public function bankInfo($params=[])
    {
        try {
            validate([
                'areaCode'  => 'require', 
            ])->message([
                'areaCode.require'  => 'areaCode必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['areaCode']=$params['areaCode']??1;
        $data['bankName']=$params['bankName']??'';

        $res = $this->ApiService->sendTokenUnite('bankInfo',$data,'get');

        return $this->ApiService->returnTokenUnite($res);
    }

    // 商户类别查询
    public function shopType($params=[])
    {
        try {
            validate([
                'businessScene'  => 'require', 
            ])->message([
                'businessScene.require'  => 'businessScene必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $data['businessScene']=$params['businessScene']??1;
    
        $res = $this->ApiService->sendTokenUnite('shopType',$data,'get');

        return $this->ApiService->returnTokenUnite($res);
    }

    // 文件上传下载
    public function fileDo($params=[])
    {
        try {
            validate([
                'imgType'  => 'require', 
                'sourcechnl'  => 'require', 
                'isOcr'  => 'require', 
            ])->message([
                'imgType.require'  => 'imgType必须传递',    
                'sourcechnl.require'  => 'sourcechnl必须传递',    
                'isOcr.require'  => 'isOcr必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        // $data['file']=request()->file('file');
        $file=$_FILES['file'];
        $tmpFilePath = $file['tmp_name'];
        $fileName = $file['name'];
        $fileMime = $file['type'];

        $data['file']=new CURLFile($tmpFilePath, $fileMime, $fileName);
        $data['imgType']=$params['imgType']??'';
//        $data['prefix']=$params['prefix']??'';
        $data['sourcechnl']=$params['sourcechnl']??1;
        $data['isOcr']=$params['isOcr']??false;
    
        $res = $this->ApiService->sendTokenUnite('fileDo',$data,'post','form-data');

        if(!isset($res['error'])){
//            $res['url'] = str_replace('//','/',$res['url']);
//            $res['showUrl'] = str_replace('//','/',$res['showUrl']);
            return result_success('success',$res);
        }else{
            return result_error($res["message"]??'请求失败');
        }
    }


    public function fileUpload()
    {

        $url = 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/ugc/20250424/07939257907cb281520be1b05e180fb1.jpg';

        $content = file_get_contents($url);
        // 2. 创建临时文件
        $tempFile = tempnam(sys_get_temp_dir(), 'oss_');
        file_put_contents($tempFile, $content);



        // 3. 准备上传数据
        $data = [
            'file' => new CURLFile(
                $tempFile,
                mime_content_type($tempFile), // 自动检测MIME类型
                basename($url) // 使用URL中的文件名
            ),
            'imgType' =>  mime_content_type($tempFile),
            'sourcechnl' =>  1,
            'isOcr' =>  false
        ];

// 4. 发送请求
        $res = $this->ApiService->sendTokenUnite('fileDo', $data, 'post', 'form-data');
dd($res);

        // $data['file']=request()->file('file');
        $file=$binaryStream;
        $tmpFilePath = $file['tmp_name'];
        $fileName = $file['name'];
        $fileMime = $file['type'];

        $data['file']=new CURLFile($tmpFilePath, $fileMime, $fileName);
        $data['imgType']=$params['imgType']??'';
//        $data['prefix']=$params['prefix']??'';
        $data['sourcechnl']=$params['sourcechnl']??1;
        $data['isOcr']=$params['isOcr']??false;

        $res = $this->ApiService->sendTokenUnite('fileDo',$data,'post','form-data');

        if(!isset($res['error'])){
//            $res['url'] = str_replace('//','/',$res['url']);
//            $res['showUrl'] = str_replace('//','/',$res['showUrl']);
            return result_success('success',$res);
        }else{
            return result_error($res["message"]??'请求失败');
        }
    }

// ----------------------------------sdk接口-------------------------------------

    // 1.聚合支付： 支付预下单，获取订单号，支付结果回调通知
    public function createPayOrder($params)
    {
        try {
            validate([
                'merchant_no'  => 'require', 
                'term_no'  => 'require', 
                'out_trade_no'  => 'require', 
                'account_type'  => 'require', 
                'trans_type'  => 'require', 
                'total_amount'  => 'require', 
                'location_info'  => 'require', 
                'subject'  => 'require', 
                'acc_busi_fields'  => 'require', 
            ])->message([
                'merchant_no.require'  => 'merchant_no必须传递',    
                'term_no.require'  => 'term_no必须传递',    
                'out_trade_no.require'  => 'out_trade_no必须传递',    
                'account_type.require'  => 'account_type必须传递',    
                'trans_type.require'  => 'trans_type必须传递',    
                'total_amount.require'  => 'total_amount必须传递',    
                'location_info.require'  => 'location_info必须传递',    
                'subject.require'  => 'subject必须传递',    
                'acc_busi_fields.require'  => 'acc_busi_fields必须传递',    
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $payBody["merchant_no"]=$params['merchant_no'];//商户号
        $payBody["term_no"]=$params['term_no'];//终端号
        $payBody["out_trade_no"]=$params['out_trade_no'];//商户交易流水号
        $payBody["account_type"]=$params['account_type'];//钱包类型微信：WECHAT 支付宝：ALIPAY 银联：UQRCODEPAY 翼支付: BESTPAY 苏宁易付宝: SUNING 拉卡拉支付账户：LKLACC 网联小钱包：NUCSPAY 京东钱包：JD
        $payBody["trans_type"]=$params['trans_type'];//接入方式41:NATIVE（（ALIPAY，云闪付支持，京东白条分期）51:JSAPI（微信公众号支付，支付宝服务窗支付，银联JS支付，翼支付JS支付, 拉卡拉钱包支付, 支付宝小程序支付）71:微信小程序支付61:APP支付（微信APP支付）
        $payBody["total_amount"]=$params['total_amount'];//金额,分
        $payBody["location_info"]=json_decode($params['location_info']);//地址位置信息
        $payBody["subject"]=$params['subject'];//订单标题(微信必传)
        $payBody["notify_url"]=  $this->config[ 'order_notify_url']  ;//回调地址
        $payBody["settle_type"]=$params['settle_type']??0;//结算方式0
        $payBody["acc_busi_fields"]=json_decode($params['acc_busi_fields']);//账户端业务信息域

        \think\facade\Log::info('拉卡拉--聚合支付收款--请求参数---:' . json_encode($payBody));
        $res = $this->ApiService->sendV3Unite('createPayOrder',$payBody);
        \think\facade\Log::info('拉卡拉--聚合支付收款--请求结果---:' . json_encode($res));

        if(isset($res['code'])&&$res['code']== self::REQ_STATUS_SUCCESS){
            $appid=$params['appid'];//appid
            $app_type=get_app_type_int($params['app_type']);//app_type
            $data=$res['resp_data'];//请求返回结果
            $third_number=$data['trade_no'];//聚合支付平台订单号
            $call_number=$params['out_trade_no'];//调用方单号

        // 新增总订单(金额单位统一：分)
            $orderData['appid'] = $appid;
            $orderData['third_number'] = $third_number;
            $orderData['call_number'] =  $call_number;
            $orderData['app_type'] = $app_type;

            $orderData['merchant_no'] =  $data['merchant_no'];//商户号
            $orderData['log_no'] = $data['log_no'];//拉卡拉对账单流水号
            $orderData['settle_merchant_no'] = $data['settle_merchant_no'];//拉卡拉分配的商户号
            $orderData['settle_term_no'] = $data['settle_term_no'];//拉卡拉分配的业务终端号
            $orderData['acc_resp_fields'] = json_encode($data['acc_resp_fields']);//账户端返回信息域

            $orderData['term_no'] = $params['term_no'];//终端号
            $orderData['trans_type'] = $params['trans_type'];//接入方式
            $orderData['total_amount'] = $params['total_amount'];//金额，分
            $orderData['settle_type'] = $params['settle_type']??0;//结算类型
            $orderData['acc_busi_fields'] = $params['acc_busi_fields'];//账户端业务信息域，存有用户标识，例如微信openid
        
            $add_order = (new Order)->orderCreate($orderData);

            $sys_number=$add_order['data']['sys_number'];//支付系统订单号

        // 新增拉卡拉订单(金额单位统一：分)
            $lklOrderData['appid'] = $appid;
            $lklOrderData['third_number'] = $third_number;
            $lklOrderData['sys_number'] = $sys_number;
            $lklOrderData['call_number'] =  $call_number;
            $lklOrderData['app_type'] = $app_type;

            $lklOrderData['merchant_no'] =  $data['merchant_no'];//商户号
            $lklOrderData['log_no'] = $data['log_no'];//拉卡拉对账单流水号
            $lklOrderData['settle_merchant_no'] = $data['settle_merchant_no'];//拉卡拉分配的商户号
            $lklOrderData['settle_term_no'] = $data['settle_term_no'];//拉卡拉分配的业务终端号
            $lklOrderData['acc_resp_fields'] = json_encode($data['acc_resp_fields']);//账户端返回信息域

            $lklOrderData['term_no'] = $params['term_no'];//终端号
            $lklOrderData['trans_type'] = $params['trans_type'];//接入方式
            $lklOrderData['total_amount'] = $params['total_amount'];//金额，分
            $lklOrderData['settle_type'] = $params['settle_type']??0;//结算类型
            $lklOrderData['acc_busi_fields'] = $params['acc_busi_fields'];//账户端业务信息域，存有用户标识，例如微信openid

            $add_lkl_order = (new OrderLakala())->lklOrderCreate($lklOrderData);
        
            if($add_order['success']){
               $result_data=[
                    "sys_number"=>$sys_number ,//sys_number
                    "acc_resp_fields"=>$data['acc_resp_fields'] ,//前端用acc_resp_fields里的prepay_id拉起支付
                    "order_type"=>'lakala'
                ];
               return result_success('success',$result_data);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 

        return $this->ApiService->returnV3Unite($res);
    }

    // 2.聚合支付：支付订单查询
    public function queryPayOrder($params)
    {
        try {
            validate([
                'merchant_no'  => 'require', 
                'term_no'  => 'require', 
            ])->message([
                'merchant_no.require'  => 'merchant_no必须传递',    
                'term_no.require'  => 'term_no必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["merchant_no"]=$params["merchant_no"];//商户号
        $payBody["term_no"]=$params["term_no"];//终端号
        isset($params["out_trade_no"])?$payBody["out_trade_no"]=$params["out_trade_no"]:"";//下单时的商户请求流水
        isset($params["trade_no"])?$payBody["trade_no"]=$params["trade_no"]:"";//拉卡拉交易流水号
       
        $res = $this->ApiService->sendV3Unite('queryPayOrder',$payBody);

        return $this->ApiService->returnV3Unite($res);
    }

    // 3.聚合支付：取消订单,退单，可部分退款
    public function cancelPayOrder($params)
    {
        try {
            validate([
                'merchant_no'  => 'require', 
                'term_no'  => 'require', 
                'out_trade_no'  => 'require', 
                'refund_amount'  => 'require', 
                'location_info'  => 'require', 
            ])->message([
                'merchant_no.require'  => 'merchant_no必须传递',    
                'term_no.require'  => 'term_no必须传递',    
                'out_trade_no.require'  => 'out_trade_no必须传递',    
                'refund_amount.require'  => 'refund_amount必须传递',    
                'location_info.require'  => 'location_info必须传递',    

            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $payBody["merchant_no"]=$params["merchant_no"];
        $payBody["term_no"]=$params["term_no"];
        $payBody["out_trade_no"]=$params["out_trade_no"];//退款流水号
        $payBody["refund_amount"]=$params["refund_amount"];//退款金额,分

        isset($params["origin_out_trade_no"])?$payBody["origin_out_trade_no"]=$params["origin_out_trade_no"]:'';//商户交易流水号
        isset($params["origin_trade_no"])?$payBody["origin_trade_no"]=$params["origin_trade_no"]:'';//拉卡拉交易流水号
        isset($params["origin_log_no"])?$payBody["origin_log_no"]=$params["origin_log_no"]:'';//对账单中的交易流水
        
        isset($params["refund_reason"])?$payBody["refund_reason"]=$params["refund_reason"]:'';//退款原因
        $payBody["location_info"]=json_decode($params["location_info"]);//地址位置信息

        \think\facade\Log::info('拉卡拉--聚合支付退款--请求参数---:' . json_encode($payBody));
        $res = $this->ApiService->sendV3Unite('cancelPayOrder', $payBody);
        \think\facade\Log::info('拉卡拉--聚合支付退款--请求结果---:' . json_encode($res));

        // $rr='{"code":"BBS00000","msg":"\u6210\u529f","resp_time":"20250717172524","resp_data":{"merchant_no":"8223310737200BP","out_trade_no":"LKL20250717172524810500","trade_no":"20250717110113131266122212188693","log_no":"66122212188693","acc_trade_no":"50101204012025071751683790323","account_type":"WECHAT","total_amount":"1","refund_amount":"1","payer_amount":"1","buyer_refund_amount":"1","trade_time":"20250717172524","origin_trade_no":"20250717110113130266222212268833","origin_out_trade_no":"P202505245037769017472900","up_iss_addn_data":"","up_coupon_info":"","fund_bill_list":"","trade_info":""}}';
        // $res=json_decode($rr,true);

        if(isset($res['code'])&&$res['code']== self::REQ_STATUS_SUCCESS){
            $appid=$params['appid'];//appid
            $app_type=get_app_type_int($params['app_type']);//app_type

            $data=$res['resp_data'];//请求返回结果
            $third_number=$data['trade_no'];//聚合支付平台退款订单号
            $call_number=$params['out_trade_no'];//调用方退款单号

            if($data['total_amount']==$data['payer_amount']){//全部退款
                $status='REFUND';//状态:全部退款
            }elseif($data['total_amount']>$data['payer_amount'] && $data['payer_amount']>0){//部分退款
                $status ='PART_REFUND';//状态:部分退款
            }else{
                $status ='';
            }

        // 新增退款总订单(金额单位统一：分)
            $orderData['third_number'] = $third_number;//聚合支付平台订单号
            $orderData['call_number'] = $call_number;//调用方订单号
            $orderData['app_type'] = $app_type;//第三方平台类型 {radio} (1:拉卡拉测试,10:拉卡拉正式)
            $orderData['appid'] = $appid;//appid
            $orderData['merchant_no'] = $data['merchant_no']??"";//商户号
            $orderData['refund_reason'] = $params['refund_reason']??"";//退款原因
            $orderData['log_no'] = $data['log_no']??"";//拉卡拉对账单流水号
            $orderData['acc_trade_no'] = $data['acc_trade_no']??"";//账户端交易流水号
            $orderData['account_type'] = $data['account_type']??"";//钱包类型微信：WECHAT 支付宝：ALIPAY 银联：UQRCODEPAY 翼支付: BESTPAY 苏宁易付宝: SUNING
            $orderData['total_amount'] = $data['total_amount']??"";//交易金额,分
            $orderData['refund_amount'] = $data['refund_amount']??"";//申请退款金额,分
            $orderData['payer_amount'] = $data['payer_amount']??"";//实际退还金额,分
            $orderData['trade_time'] = $data['trade_time']??"";//退款时间
            $orderData['origin_trade_no'] = $data['origin_trade_no']??"";//原拉卡拉订单号  
            $orderData['origin_out_trade_no'] = $data['origin_out_trade_no']??"";//原商户请求流水号
            $orderData['refun_info'] = json_encode($data);//退款消息
            $orderData['status'] = $status??"ERROR";// 状态：PART_REFUND-部分退款 REFUND-全部退款 ERROR-退款失败

            $add_order = (new OrderRefund)->orderRefundCreate($orderData);

            $sys_number=$add_order['data']['sys_number'];//支付系统订单号

        // 新增拉卡拉退款订单(金额单位统一：分)
            $lklOrderData['third_number'] = $third_number;//聚合支付平台订单号
            $lklOrderData['sys_number'] = $sys_number;//支付系统订单号
            $lklOrderData['call_number'] = $call_number;//调用方订单号
            $lklOrderData['app_type'] = $app_type;//第三方平台类型 {radio} (1:拉卡拉测试,10:拉卡拉正式)
            $lklOrderData['appid'] = $appid;//appid
            $lklOrderData['merchant_no'] = $data['merchant_no']??"";//商户号
            $lklOrderData['refund_reason'] = $params['refund_reason']??"";//退款原因
            $lklOrderData['log_no'] = $data['log_no']??"";//拉卡拉对账单流水号
            $lklOrderData['acc_trade_no'] = $data['acc_trade_no']??"";//账户端交易流水号
            $lklOrderData['account_type'] = $data['account_type']??"";//钱包类型微信：WECHAT 支付宝：ALIPAY 银联：UQRCODEPAY 翼支付: BESTPAY 苏宁易付宝: SUNING
            $lklOrderData['total_amount'] = $data['total_amount']??"";//交易金额,分
            $lklOrderData['refund_amount'] = $data['refund_amount']??"";//申请退款金额,分
            $lklOrderData['payer_amount'] = $data['payer_amount']??"";//实际退还金额,分
            $lklOrderData['trade_time'] = $data['trade_time']??"";//退款时间
            $lklOrderData['origin_trade_no'] = $data['origin_trade_no']??"";//原拉卡拉订单号  
            $lklOrderData['origin_out_trade_no'] = $data['origin_out_trade_no']??"";//原商户请求流水号
            $lklOrderData['refun_info'] = json_encode($data);//退款消息
            $lklOrderData['status'] = $status??"ERROR";// 状态：PART_REFUND-部分退款 REFUND-全部退款 ERROR-退款失败

            $add_lkl_order = (new OrderRefundLakala())->lklOrderRefundCreate($lklOrderData);

        //更新订单信息
            $orderParam['third_number'] = $data['origin_trade_no'] ?? '';//原拉卡拉订单号  
            $status?$orderParam['status'] =$status:'';//状态:全部退款
            $orderParam['refund_amount'] = $data['payer_amount'] ?? '';//实际退还金额,分

            $Order = new Order();
            $update_order = $Order->orderUpdate($orderParam);
       

        //更新lakala订单表
            $OrderLakala = new OrderLakala();
            $update_order_lkl = $OrderLakala->lklOrderUpdate($orderParam);
     
            if($add_order['success']){
               $result_data=[
                    "sys_number"=>$sys_number ,//sys_number
                    "total_amount"=>$data['total_amount'] ,//交易金额,分
                    "refund_apply_amount"=>$data['refund_amount'] ,//申请退款金额,分
                    "refund_payer_amount"=>$data['payer_amount'] ,//实际退还金额,分
                    "status"=>$orderParam['status']??"" ,//实际退还金额,分
                    "order_type"=>'lakala'
                ];
               return result_success('success',$result_data);
            }else{
               return result_error($add["msg"]??'保存失败');
            }
        }else{
           return result_error($res["msg"]??'请求失败');
        } 

        return $this->ApiService->returnV3Unite($res);
    }

    // 4.收银台支付：支付下单
    public function cashierPayOrder($params)
    {
        $payBody = null;
        if (isset($params)) {
            $payBody["merchant_no"] = $params["merchant_no"];
            $payBody["out_order_no"] = $params["out_order_no"];
            $payBody["total_amount"] = $params["total_amount"];
            $payBody["order_efficient_time"] = $params["order_efficient_time"];
            $payBody["order_info"] = $params["order_info"];
            $payBody["notify_url"]=env("lakala.notify_url","");//回调地址
            $payBody["settle_type"]=env("lakala.settle_type",0);//结算方式
        }
        $res = $this->ApiService->sendV3Unite('cashierPayOrder', $payBody);
        return $this->ApiService->returnV3Unite($res);
    }

    // 5.收银台支付：支付关单
    public function cashierClosePayOrder($params)
    {
        $payBody = null;
        if (isset($params)) {
        }
        $res = $this->ApiService->sendV3Unite('cashierClosePayOrder', $payBody);
        return $this->ApiService->returnV3Unite($res);
    }

    // 6.收银台支付：支付查询
    public function cashierQueryPayOrder($params)
    {
        $payBody = null;
        if (isset($params)) {
        }
        $res = $this->ApiService->sendV3Unite('cashierQueryPayOrder', $payBody);
        return $this->ApiService->returnV3Unite($res);
    }

    // 7.收银台支付：支付取消
    public function cashierCancelPayOrder($params)
    {
        $payBody = null;
        if (isset($params)) {
        }
        $res = $this->ApiService->sendV3Unite('cashierCancelPayOrder', $payBody);
        return $this->ApiService->returnV3Unite($res);
    }

    // 8.收银台支付：支付取消查询
    public function cashierCancelPayOrderQuery($params)
    {
        $payBody = null;
        if (isset($params)) {
        }
        $res = $this->ApiService->sendV3Unite('cashierCancelPayOrderQuery', $payBody);
        return $this->ApiService->returnV3Unite($res);
    }

    // 卡BIN查询--sdk
    public function cardBin($params)
    {
        try {
            validate([
                'version'  => 'require', 
                'orgCode'  => 'require', 
                'cardNo'  => 'require', 
            ])->message([
                'version.require'  => 'version必须传递',    
                'orgCode.require'  => 'orgCode必须传递',
                'cardNo.require'  => 'cardNo必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["version"]=$params["version"];//接口版本号
        $payBody["orderNo"]=date('YmdHis').rand(10000000,99999999);//订单编号（便于后续跟踪排查问题及回调消息匹配）
        $payBody["orgCode"]=$params["orgCode"];//机构代码
        $payBody["cardNo"]=$params["cardNo"];//银行卡号

        $res = $this->ApiService->sendV3Unite('cardBin',$payBody);
// var_dump($res);exit;
        return $this->ApiService->returnV3Unite($res);
    }

    // 附件上传--sdk
    public function uploadFile($params)
    {
        try {
            validate([
                'version'  => 'require', 
                'orgCode'  => 'require', 
                'cardNo'  => 'require', 
                'attType'  => 'require', 
                'attExtName'  => 'require', 
                'attContext'  => 'require', 
            ])->message([
                'version.require'  => 'version必须传递',    
                'orgCode.require'  => 'orgCode必须传递',
                'cardNo.require'  => 'cardNo必须传递',
                'attType.require'  => 'attType必须传递',
                'attExtName.require'  => 'attExtName必须传递',
                'attContext.require'  => 'attContext必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["version"]=$params["version"];//接口版本号
        $payBody["orderNo"]=date('YmdHis').rand(10000000,99999999);//订单编号（便于后续跟踪排查问题及回调消息匹配）
        $payBody["orgCode"]=$params["orgCode"];//机构代码
        $payBody["attType"]=$params["attType"];//附件类型 附件类型枚举，ID_CARD_FRONT
        $payBody["attExtName"]=$params["attExtName"];//附件扩展名称 jpg，png，pdf
        $payBody["attContext"]=$params["attContext"];//附件内容 文件内容 BASE64格式  

        $res = $this->ApiService->sendV3Unite('uploadFile',$payBody);
// var_dump($res);exit;
        return $this->ApiService->returnV3Unite($res);
    }

    // -----------------------------------------回调处理--------------------------

    // 分账状态回调
    public function centsStatusNotify($param=[])
    {
    
    }

    // 分账状态回调
    public function ecStatusNotify($param=[])
    {
        $where['ec_apply_id'] = $param["ecApplyId"];
        $ecApply = LakalaEcApply::where($where)->order('id', 'desc')->find();

        if ( $ecApply->status == LakalaEcApply::STATUS_COMPLETED ) {
            $ecApply->ec_no = $param['ecNo'];
        }
        $ecStatus = LakalaEcApply::getEcStatus($param['ecStatus']);
        $ecApply->status = $ecStatus;
        $ecApply->notify_response = $param;
        $ecApply->save();

        //回调给 调用平台
        $appid = $orderdetail['appid'] ?? '';
        $notify_url = $ecApply->ret_url;
        if ( empty($notify_url) ) {
            if (!empty($appid)){//获取回调转发地址
                $notify_url = Db::name("app_interface_config")
                    ->where('appid', $appid)
                    ->value('ec_notify_url');
            }

            if (empty($notify_url)){
                \think\facade\Log::error("----------ec状态回调----------回调地址不存在-------------".json_encode($param));
                return '回调地址不存在';
            }
        }

        //转发到终端平台
        $li['ec_apply_id']=$param["ecApplyId"];//商户号
        $li['ec_no']=$param["ecNo"]; //电子合同号
        $li['status_str']= LakalaEcApply::getEcStatusStr($param["ecStatus"]);//状态str
        $li['status']= $ecStatus;//状态

        $post_res = curl_post($notify_url, $li,[],'json');
        $res=json_decode($post_res,true);

        if (isset($res['res']) && $res['res']=="success") {
            return json_encode(["code"=>self::BACK_STATUS_SUCCESS,"message"=>$this->getV3StatusStr(self::BACK_STATUS_SUCCESS)]);
        }else{
            \think\facade\Log::error("----------ec状态回调----------回调转发结果失败-------------".json_encode($param).' -- $post_res  '.$post_res);
            return '回调转发结果失败';
        }

    }

    // 门店状态回调
    public function shopStatusNotify($param=[])
    {
        $where['merchantNo'] =$param["customerNo"];
        $orderdetail =Shop::where($where)->order('id', 'desc')->find();

        $appid = $orderdetail['appid'] ?? '';
        if (!empty($appid)){//获取回调转发地址
            $notify_url = Db::name("app_interface_config")
                ->where('appid', $appid)
                ->value('shop_notify_url');
        }

        if (empty($notify_url)){
            \think\facade\Log::error("----------门店状态回调----------回调地址不存在-------------".json_encode($param));
            return '回调地址不存在';
        }

        $shopParam['status'] =  \app\api\model\Shop::getLklApproveStatusInt($param["status"]);//状态
        $shopParam['merchantNo'] =$param["customerNo"];//商户号
        $shopParam['notify_info'] = json_encode($param);

        //更新商铺信息
        $shop = new Shop();
        $res_shop = $shop->shopUpdate($shopParam);
        if(!$res_shop["success"]){
            \think\facade\Log::error("----------门店状态回调----------商铺信息表保存失败----".json_encode($shopParam)."结果:".json_encode($res_shop));
            return '订单总表保存失败';
        }

        //转发到终端平台
        $li['merchantNo']=$param["customerNo"];//商户号
        $li['status_str']=\app\api\model\Shop::getLklApproveStatusStr($param["status"]);//状态str
        $li['status']= \app\api\model\Shop::getLklApproveStatusInt($param["status"]);//状态
       
        $post_res = curl_post($notify_url, $li,[],'json');
        $res=json_decode($post_res,true);

        if (isset($res['res']) && $res['res']=="success") {
            return json_encode(["code"=>self::BACK_STATUS_SUCCESS,"message"=>$this->getV3StatusStr(self::BACK_STATUS_SUCCESS)]);
        }else{
            \think\facade\Log::error("----------门店状态回调----------回调转发结果失败-------------".json_encode($param));
            return '回调转发结果失败';
        }
    }

    // 订单状态回调
    public function orderStatusNotify($param=[])
    {

        $where['third_number'] =  $param['trade_no'];
        $orderdetail =Order::where($where)->order('id', 'desc')->find();

        $appid = $orderdetail['appid'] ?? '';
        $sys_number = $orderdetail['sys_number'] ?? '';
        if (!empty($appid)){//获取回调转发地址
            $notify_url = Db::name("app_interface_config")
                ->where('appid', $appid)
                ->value('order_notify_url');
        }

        if (empty($notify_url)){
            \think\facade\Log::error("----------订单状态回调----------回调地址不存在-------------".json_encode($param));
            return '回调地址不存在';
        }

        $orderParam['third_number'] = $param['trade_no'] ?? '';//聚合支付平台订单号
        $orderParam['status'] = $param['trade_status'] ?? '';//状态
        $orderParam['payer_amount'] = $param['payer_amount'] ?? '';//支付金额，分
        $orderParam['callback_info'] = json_encode($param);//下单回调信息

        //更新订单基本信息
        $Order = new Order();
        $res_order = $Order->orderUpdate($orderParam);
        if(!$res_order["success"]){
            \think\facade\Log::error("----------订单状态回调----------订单总表保存失败----".json_encode($orderParam)."结果:".json_encode($res_order));
            return '订单总表保存失败';
        }

        //更新lakala订单表
        $OrderLakala = new OrderLakala();
        $res_order_lkl = $OrderLakala->lklOrderUpdate($orderParam);
        if(!$res_order_lkl["success"]){
            \think\facade\Log::error("----------订单状态回调----------订单lakala表保存失败----".json_encode($orderParam)."结果:".json_encode($res_order_lkl));
            return '订单lakala表保存失败';
        }

        //转发到终端平台
        $li['sys_number']=$sys_number;//支付系统订单号
        $li['status']=$param['trade_status'] ?? '';//状态
        $li['payer_amount']=$param['payer_amount'] ?? '';//实付金额
        $li['status_str']=\app\api\model\Order::getStatusStr($param["trade_status"]);//状态str

        $post_res = curl_post($notify_url, $li,[],'json');
        $res=json_decode($post_res,true);

        if (isset($res['res']) && $res['res']=="success") {
            return json_encode(["code"=>self::BACK_STATUS_SUCCESS,"message"=>$this->getV3StatusStr(self::BACK_STATUS_SUCCESS)]);
        }else{
            \think\facade\Log::error("----------订单状态回调----------回调转发结果失败-------------".json_encode($param));
            return '回调转发结果失败';
        }
    }


    // ------------------------------------分账相关------------------------------------


    // 商户分账业务开通申请（第一步，商户开通分账）
    public function applyLedgerMer($params)
    {
        try {
            validate([
                'version'  => 'require', 
                'orgCode'  => 'require', 
                'merCupNo'  => 'require', 
                'contactMobile'  => 'require', 
                'splitLowestRatio'  => 'require', 
                'splitEntrustFileName'  => 'require', 
                'splitEntrustFilePath'  => 'require', 
            ])->message([
                'version.require'  => 'version必须传递',    
                'orgCode.require'  => 'orgCode必须传递',
                'merCupNo.require'  => 'merCupNo必须传递',
                'contactMobile.require'  => 'contactMobile必须传递',
                'splitLowestRatio.require'  => 'splitLowestRatio必须传递',
                'splitEntrustFileName.require'  => 'splitEntrustFileName必须传递',
                'splitEntrustFilePath.require'  => 'splitEntrustFilePath必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["version"]=$params["version"];//接口版本号
        $payBody["orderNo"]=date('YmdHis').rand(10000000,99999999);//订单编号（便于后续跟踪排查问题及回调消息匹配）
        $payBody["orgCode"]=$params["orgCode"];//机构代码
        $payBody["merCupNo"]=$params["merCupNo"];//拉卡拉内部商户号
        $payBody["contactMobile"]=$params["contactMobile"];//联系手机号
        $payBody["splitLowestRatio"]=$params["splitLowestRatio"];//最低分账比例（百分比，支持2位精度）例 70 或 70.50
        $payBody["splitEntrustFileName"]=$params["splitEntrustFileName"];//分账结算委托书文件名称
        $payBody["splitEntrustFilePath"]=$params["splitEntrustFilePath"];//分账结算委托书文件路径
        $payBody["splitRange"]=$params["splitRange"];//分账范围(ALL：全部交易MARK：带标记的交易)
        $payBody["retUrl"]=$this->config[ 'cents_notify_url'];//回调通知地址

        $res = $this->ApiService->sendV2Unite('applyLedgerMer', $payBody);

        return $this->ApiService->returnV2Unite($res);
    }
    
    // 创建分账接收方（第二步，返回分账接收方编号）
    public function applyLedgerReceiver($params)
    {
        try {
            validate([
                'version'  => 'require', 
                'orgCode'  => 'require', 
                'receiverName'  => 'require', 
                'contactMobile'  => 'require', 
                'acctNo'  => 'require', 
                'acctName'  => 'require', 
                'acctTypeCode'  => 'require', 
                'acctCertificateType'  => 'require', 
                'acctCertificateNo'  => 'require', 
                'acctOpenBankCode'  => 'require', 
                'acctOpenBankName'  => 'require', 
                'acctClearBankCode'  => 'require', 
            ])->message([
                'version.require'  => 'version必须传递',    
                'orgCode.require'  => 'orgCode必须传递',
                'receiverName.require'  => 'receiverName必须传递',
                'contactMobile.require'  => 'contactMobile必须传递',
                'acctNo.require'  => 'acctNo必须传递',
                'acctName.require'  => 'acctName',
                'acctTypeCode.require'  => 'acctTypeCode必须传递',
                'acctCertificateType.require'  => 'acctCertificateType必须传递',
                'acctCertificateNo.require'  => 'acctCertificateNo必须传递',
                'acctOpenBankCode.require'  => 'acctOpenBankCode必须传递',
                'acctOpenBankName.require'  => 'acctOpenBankName必须传递',
                'acctClearBankCode.require'  => 'acctClearBankCode必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["version"]=$params["version"];//接口版本号
        $payBody["orderNo"]=date('YmdHis').rand(10000000,99999999);//订单编号（便于后续跟踪排查问题及回调消息匹配）
        $payBody["orgCode"]=$params["orgCode"];//机构代码
        $payBody["receiverName"]=$params["receiverName"];//分账接收方名称
        $payBody["contactMobile"]=$params["contactMobile"];//联系手机号
        $payBody["acctNo"]=$params["acctNo"];//收款账户卡号
        $payBody["acctName"]=$params["acctName"];//收款账户名称
        $payBody["acctTypeCode"]=$params["acctTypeCode"];//收款账户账户类型 57：对公 58：对私
        $payBody["acctCertificateType"]=$params["acctCertificateType"];//收款账户证件类型17 身份证，18 护照，19 港澳居民来往内地通行证 20 台湾居民来往内地通行证
        $payBody["acctCertificateNo"]=$params["acctCertificateNo"];//收款账户证件号
        $payBody["acctOpenBankCode"]=$params["acctOpenBankCode"];//收款账户开户行号
        $payBody["acctOpenBankName"]=$params["acctOpenBankName"];//收款账户开户名称
        $payBody["acctClearBankCode"]=$params["acctClearBankCode"];//收款账户清算行行号

        // 对公必传
        $payBody["licenseNo"]=$params["licenseNo"];//营业执照号码(收款账户账户类型为对公，必须上送)
        $payBody["licenseName"]=$params["licenseName"];//营业执照名称(收款账户账户类型为对公，必须上送)
        $payBody["legalPersonName"]=$params["legalPersonName"];//法人姓名(收款账户账户类型为对公，必须上送)
        $payBody["legalPersonCertificateType"]=$params["legalPersonCertificateType"];//法人证件类型17 身份证，18 护照，19 港澳居民来往内地通行证 20 台湾居民来往内地通行证(收款账户账户类型为对公，必须上送)
        $payBody["legalPersonCertificateNo"]=$params["legalPersonCertificateNo"];//法人证件号(收款账户账户类型为对公，必须上送)

        $res = $this->ApiService->sendV2Unite('applyLedgerReceiver',$payBody);

        return $this->ApiService->returnV2Unite($res);
    }

    // 分账关系绑定申请（第三步，绑定）
    public function applyBind($params)
    {
        try {
            validate([
                'version'  => 'require', 
                'orgCode'  => 'require', 
                'merCupNo'  => 'require', 
                'contactMobile'  => 'require', 
                'receiverNo'  => 'require', 
                'entrustFileName'  => 'require', 
                'entrustFilePath'  => 'require', 
            ])->message([
                'version.require'  => 'version必须传递',    
                'orgCode.require'  => 'orgCode必须传递',
                'merCupNo.require'  => 'merCupNo必须传递',
                'contactMobile.require'  => 'contactMobile必须传递',
                'receiverNo.require'  => 'receiverNo必须传递',
                'entrustFileName.require'  => 'entrustFileName必须传递',
                'entrustFilePath.require'  => 'entrustFilePath必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["version"]=$params["version"];//接口版本号
        $payBody["orderNo"]=date('YmdHis').rand(10000000,99999999);//订单编号（便于后续跟踪排查问题及回调消息匹配）
        $payBody["orgCode"]=$params["orgCode"];//机构代码
        $payBody["merCupNo"]=$params["merCupNo"];//拉卡拉内部商户号
        $payBody["contactMobile"]=$params["contactMobile"];//联系手机号
        $payBody["receiverNo"]=$params["receiverNo"];//分账接收方编号
        $payBody["entrustFileName"]=$params["entrustFileName"];//合作协议名称
        $payBody["entrustFilePath"]=$params["entrustFilePath"];//合作协议路径
        $payBody["retUrl"]=$this->config[ 'cents_notify_url'];//回调通知地址

        $res = $this->ApiService->sendV2Unite('applyBind', $payBody);

        return $this->ApiService->returnV2Unite($res);
    }
    
    // 账户余额查询（第四步，查余额（payType=03））
    public function balanceQuery($params)
    {
        try {
            validate([
                'orgNo'  => 'require', 
                'merchantNo'  => 'require', 
                'payType'  => 'require', 
            ])->message([
                'orgNo.require'  => 'orgNo必须传递',    
                'merchantNo.require'  => 'merchantNo必须传递',    
                'payType.require'  => 'payType必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }

        $payBody["orgNo"]=$params["orgNo"];//bmcp机构号
        $payBody["merchantNo"]=$params["merchantNo"];//商户号 或 receiveNo 或 商户用户编号
        $payBody["payType"]=$params["payType"];//账号类型（01：收款账户，02：付款账户，03：分账商户账户，04：分账接收方账户，05：充值代付账户，06：结算代付账户）- 未上送则默认为01
     
        $res = $this->ApiService->sendV2Unite('balanceQuery', $payBody);

        return $this->ApiService->returnV2Unite($res);
    }

    // 分账（第五步，分账）
    public function balanceSeparate($params)
    {
        try {
            validate([
                'merchant_no'  => 'require', 
                'total_amt'  => 'require', 
            ])->message([
                'merchant_no.require'  => 'merchant_no必须传递',    
                'total_amt.require'  => 'total_amt必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["merchant_no"]=$params["merchant_no"];//商户号
        $payBody["out_separate_no"]=date('YmdHis').rand(10000000,99999999);//商户分账指令流水号，每个商户号下唯一，否则会校验失败
        $payBody["total_amt"]=$params["total_amt"];//分账总金额 分

       
        $res = $this->ApiService->sendV3Unite('balanceSeparate',$payBody);

        return $this->ApiService->returnV3Unite($res);
    }
    
    // 账管家余额查询（第六步，查钱包余额）
    public function ewalletBalanceQuery($params)
    {
        try {
            validate([
                'orgNo'  => 'require', 
                'merchantNo'  => 'require', 
                'payType'  => 'require', 
            ])->message([
                'orgNo.require'  => 'orgNo必须传递',    
                'merchantNo.require'  => 'merchantNo必须传递',
                'payType.require'  => 'payType必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["orgNo"]=$params["orgNo"];//bmcp机构号
        $payBody["merchantNo"]=$params["merchantNo"];//商户号 或 receiveNo 或 商户用户编号
        $payBody["payType"]=$params["payType"];//账号类型（01：收款账户，02：付款账户，03：分账商户账户，04：分账接收方账户，05：充值代付账户，06：结算代付账户）- 未上送则默认为01
     
        $res = $this->ApiService->sendV2Unite('ewalletBalanceQuery',$payBody);

        return $this->ApiService->returnV2Unite($res);
    }

    // 账管家提现D1（第七步，提现）
    public function ewalletWithdrawD1($params)
    {
        try {
            validate([
                'orgNo'  => 'require', 
                'merchantNo'  => 'require', 
                'drawAmt'  => 'require', 
            ])->message([
                'orgNo.require'  => 'orgNo必须传递',    
                'merchantNo.require'  => 'merchantNo必须传递',
                'drawAmt.require'  => 'drawAmt必须传递',
            ])->check($params);
        } catch (ValidateException $e) {
            output_error($e->getError());
        }
       
        $payBody["orgNo"]=$params["orgNo"];//bmcp机构号
        $payBody["merchantNo"]=$params["merchantNo"];//商户号 或 receiveNo 或 商户用户编号
        $payBody["drawAmt"]=$params["drawAmt"];//提现金额（单位：元）
     
        $res = $this->ApiService->sendV2Unite('ewalletWithdrawD1',$payBody);

        return $this->ApiService->returnV2Unite($res);
    }


    /**
     * 使用私钥加密数据
     *
     * @param array $data 要加密的数据
     * @return string 加密后的字符串
     */
    public function encryptWithPrivateKey(array $data): string
    {
        $privateKey = env('lakala.push_private_key');
        $str = json_encode($data);
        return $this->ApiService->privateKeyDecrypt($str, $privateKey);
    }

    /**
     * 使用公钥解密数据
     *
     * @param string $encryptedData 加密的数据
     * @return array 解密后的数组
     */
    public function decryptWithPublicKey(string $encryptedData): array
    {
        $publicKey = env('lakala.push_public_key');
        $decrypted = $this->ApiService->publicKeyDecrypt($encryptedData, $publicKey);
        return json_decode($decrypted, true);
    }

    /**
     * 发送加密请求并解密响应
     *
     * @param string $endpoint 接口端点
     * @param array $data 请求数据
     * @return array 响应数据
     */
    public function sendEncryptedRequest(string $endpoint, array $data): array
    {
        $encryptedData = $this->encryptWithPrivateKey($data);
        $response = $this->ApiService->sendTokenUnite($endpoint, ['data' => $encryptedData]);

        if (isset($response['code']) && $response['code'] == '000000') {
            return $this->decryptWithPublicKey($response['data']);
        }

        return [];
    }
}